bonaca bonaca - 6 months ago 11
CSS Question

Top margin of first child and bottom margin of last child

HTML

<div class="lev1">level1</div>
<div class="lev2wrap">
<div class="lev2">level2</div>
<div class="lev2">level2</div>
<div class="lev2">level2</div>
<div class="lev2">level2</div>
</div>


CSS

.lev1{
background:lightblue;
}
.lev2wrap{
background:gold;
}
.lev2{
background:#999999;
margin:10px 0;
}


Why does the first instance of
lev2
not have a top margin of
10px
, and why does the last instance of
lev2
not have a bottom margin of
10px
?

Instead,
lev2wrap
has a top and bottom margin, but that's not a CSS instruction.

JSFIDDLE

Answer

Because of collapsing margins.

Top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the margins combined into it, a behavior known as margin collapsing.

Margin collapsing occurs in three basic cases:

  • Adjacent siblings
  • Parent and first/last child
  • Empty blocks

To have the margin of lev2wrap show, add overflow: auto to it:

.lev2wrap {
  background: gold;
  overflow: auto;
}

jsFiddle example