How do nested vertical margin collapses work?

Two-ish rules to remember:

  1. If margins touch, they collapse.
  2. Nested items “snuggle” if only margin separates them.
  3. Elements outside the “Flow” behave differently. That is, this behavior does not apply the same to floated, or position:fixed, or position:absolute elements.

So for this HTML (nested divs) :

<div id="outer"> 
    <div id="inner">
        A
    </div>
</div> 

and this initial CSS:

#outer {
    margin-top:10px;
    background:blue;
    height: 100px;
}
#inner {
    margin-top:20px;
    background:red;
    height: 33%;   
    width: 33%;
}

The margin collapses to the max of the touching margins and the nested div “snuggles” to the start of the container, like so: (See it at jsFiddle.)
Nested margin collapse

But, the moment the two margins are separated — by a border or by preceding content in the container, for example — the margins no longer touch, so they no longer collapse.

EG, just a little, non-breaking white-space , like so:

<div id="outer">&nbsp;
    <div id="inner">
        A
    </div>
</div>

kills the collapse : (See that at jsFiddle.)
Nested margin doesn't collapse

Using a border, instead of leading text : (Fiddle)
no-collapse, border

Leave a Comment