2

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>
FegaDev
  • 31
  • 4
  • 1
    Adding any dimension be it margin, padding, width, height border etc increses the actual size of an element thereby increasing the size of its containing parent. – Steve Tomlin May 21 '22 at 04:13
  • 1
    please don't use the answer you accept in a real project, that's not the correct way to fix the issue. – Temani Afif May 21 '22 at 13:11

2 Answers2

3

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.

Shikhar Awasthi
  • 1,172
  • 1
  • 3
  • 13
1

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>
Agilan I
  • 212
  • 3
  • 5