Home > OS >  Put Margin in Div
Put Margin in Div

Time:05-21

I have a doubt . When I'm trying put margin in the second div. Why element all element include his father take this margin ? I just want the child div to have the margin and be separated from the parent container. Thanks everybody!

#divFather {
    height:100px;
    width:800px;
    text-align:center;
    background-color:blue;
}
#divChild {
    height:50px;
    width:400px;
                 /* margin: 15px 0px */
    background-color:red;
}
<html>
    <head>
        <title>Page</title>
        <link rel="stylesheet" type="text/css" href="estilos.css" />
    </head>
    <body>
         <div id="divFather">
             <div id="divChild">Margin</div>
         </div>
    </body>
</html>

CodePudding user response:

This is called Collapsing margins. You can read more about this in attached link. To fix this you can use either use padding on parent element or another approach is to set overflow to auto of parent div.

CodePudding user response:

This is due to the margin overlap problem of static positioned elements. This could be fixed by adding position: relative; to the parent element and position: absolute to the child element.

#divFather {
    height:100px;
    width:800px;
    text-align:center;
    background-color:blue;
    position: relative;
}
#divChild {
    height:50px;
    width:400px;
    margin: 15px 0px;
    background-color:red;
    position: absolute;
}
<html>
    <head>
        <title>Page</title>
        <link rel="stylesheet" type="text/css" href="estilos.css" />
    </head>
    <body>
         <div id="divFather">
             <div id="divChild">Margin</div>
         </div>
    </body>
</html>

  • Related