Let's tackle this issue head-on:
When you eliminate the height css style on the outer div, you'll notice that the inner div moves down.
This phenomenon is known as Margin Collapsing:
When there is no border, padding, inline part, block formatting context created, or clearance to separate the margin-bottom of a block from the margin-bottom of its last child, the margins collapse. This results in the collapsed margin extending beyond the parent.
Even margins that are zero will follow these rules, causing the margin of a first/last child to extend outside its parent, regardless of the parent's margin being zero or not.
The collapse of the child margin with the parent margin causes the 16px margin to be considered part of the parent.
However, by defining a height
, you prevent margin collapsing.
According to the W3 Box Model spec*:
Two margins are adjoining if and only if:
- Both belong to vertically-adjacent box edges, forming one of the specified pairs, such as the bottom margin of a last in-flow child and bottom margin of its parent if the parent has a 'auto' computed height.
With the absence of margin collapsing, the child's margin simply attempts to increase the height of the outer div, which is not reflected due to the parent having a fixed height of 100px
.
However, what if we disrupt the collapse in a different manner? Would the height increase by 16px
?
Two margins are adjoining if and only if:
- no line boxes, no clearance, no padding, and no border separate them
To test this theory, let's introduce a border to violate this rule.
.outer {
background: yellow;
border-bottom: 1px solid black;
}
.inner {
height: 100px;
background: green;
margin-bottom: 16px;
}
.under {
background: red;
height: 10px;
}
<div class="outer">
<div class="inner"></div>
</div>
<div class="under"></div>
As anticipated, the margins do not collapse, causing the child's margin to try and increase the parent's height. Without a height
property on the parent to offset this, the parent's height expands to 116px
.
* Although this references an older spec, the behavior remains consistent. In fact, newer spec documents often refer to this one.