0

I have a very small code:

.parent{
  box-sizing: border-box;
}
.child{
  height: 100px;
  margin: 20px;
  background: red;
}
.a1{
  background: green;
}
<!DOCTYPE html>
<html>    
  <head>         
  </head>

  <body>
    <div class="parent">
        <div class="child"></div>
        <div class="child a1"></div>
    </div>
  </body>
</html>

the height of .parent is showing only 220px, but if we calculate as per child's height+margin it should be 280. I am unable to understand

Jsfiddle is jsfiddle

Arnab
  • 4,216
  • 2
  • 28
  • 50
raju
  • 6,448
  • 24
  • 80
  • 163

2 Answers2

1

That's the phenomenon know as "collapsing margins" (google it): margins of parent and child are merged, only the larger one of them is applied to the parent.

If necessary, you can avoid that by adding a tiny padding to the parent (1px):

body {
  background: #ddd;
}

.parent {
  box-sizing: border-box;
  padding: 1px;
  background: #fff;
}

.child {
  height: 100px;
  margin: 20px;
  background: red;
}

.a1 {
  background: green;
}
<div class="parent">
  <div class="child"></div>
  <div class="child a1"></div>
</div>

Addition: The same applies to the body element, which has a default margin (5px in most browsers), which is the grey area you see in my previous snippet. To avoid that, reset the margin for html and body.

And as @TEmani Afif mentioned in the comments, margin collapsing also applies between sibling elements. So in the following snippet (where I reset the body margin), you see 20px margin not only around both elements, but the margin between the two elements isn't 2 x 20px (as one could believe), but due to collapsing margins only 1 x 20px;

html,
body {
  margin: 0;
}

body {
  background: #ddd;
}

.parent {
  box-sizing: border-box;
  background: #fff;
}

.child {
  height: 100px;
  margin: 20px;
  background: red;
}

.a1 {
  background: green;
}
<div class="parent">
  <div class="child"></div>
  <div class="child a1"></div>
</div>
Johannes
  • 64,305
  • 18
  • 73
  • 130
  • it's also margin-collapsing between both childs .. parent has 0 margin ... then we have margin-collapsing with the body – Temani Afif Feb 26 '18 at 13:36
-1

You can solve it by adding border: 1px solid transparent; or you can also give padding like padding:0.5px;.

sunil kumar
  • 291
  • 1
  • 12
  • it's also margin-collapsing between both childs .. parent has 0 margin ... then we have margin-collapsing with the body – Temani Afif Feb 26 '18 at 13:38