Collapse of vertical margins

This page shows some examples showing how vertical margins collapse in the box model.
Margins collapse for block elements, and only for vertical margins. The collapse rule states that the maximum margin is used to separate flowing elements, and not the sum of the single margins.

A plain span element

First paragraph, having style MARGIN:1px 0px;

Second paragraph, having style MARGIN:20px 0px;

Third paragraph, having style MARGIN:20px 0px;

Another plain span element

Things get tricky when we consider nested elements. In the example below, the collapsed margin is the maximum value (i.e. 20px), but this margin is applied only to the container element, and not to the inner division.

<span>A plain <code>span</code> element</span> <div style="MARGIN:10px 0px; BACKGROUND-COLOR:blue;"> <div style="MARGIN:20px 0px; BACKGROUND-COLOR:cyan;">Content</div> </div>
A plain span element
Content

The issue concerning nested elements can be solved remembering the conditions that inhibits the collapsing rule:

  • border: if the outermost element has a border
  • padding: if the outermost element has some padding
  • float: if one of the nested elements is floating
  • absolute: if one of the nested elements has an absolute position
  • overflow: see next tutorial (under construction)
Applying one of these conditions in the example above, we avoid the margins collapse and we ensure that eachh single vertical margin will be respected. Notice that if the POSITION:absolute; property is used, the final behaviour changes if the set this property in the outermost element or in the innermost element.



<span>A plain <code>span</code> element</span> <div style="MARGIN:10px 0px; BACKGROUND-COLOR:blue; POSITION:absolute;"> <div style="MARGIN:20px 0px; BACKGROUND-COLOR:cyan;">Content</div> </div>
A plain span element
Content