come on gang, lets solve some margin collapsing mysteries
- margin collapsing only applies along the y axis (vertical; top and bottom margins).
- "Collapsing" is when only one margin is used (the largest one, the smaller ones are ignored and do not take vertical space), and can cause margin to go "through" many ancestor element boundaries.
-
Margins collapse when the top or bottom of two
elements touch without any vertical padding/border
or inline text content between them.
- The two elements can be at any level in the DOM (not just parent-child, but any pair of elements that share a common ancestor without padding or borders between them).
-
It can happen to two top-top margins or two
bottom-bottom margins when elements share a
common ancestor (not just between the
top-bottom margins of sibling
elements).
- When this happens, the margin can pass through the outline of one or many levels of parents.
- Multiple nested collapsing elements will mean the largest margin wins (margins are never combined, all are ignored except the largest).
- Top and bottom margins for a given element collapse independently (the top cannot affect the bottom and vice versa).
- Only happens to elements part of the normal document flow (not to floats or absolutely positioned elements).
- To avoid margin collapsing between two elements:
Example 1 ↑
Example 1 below has a DOM structure like this:
<div>
<!-- Blue dotted outline -->
<div class="parent-parent">
<!-- Orange dashed outline -->
<div class="parent">
<!-- Red square -->
<div>e-1</div>
<!-- Blue square -->
<div>e-2</div>
</div>
</div>
</div>
Play with the margins to see how they "collapse" (only the largest margin is used, smaller margins are ignored). The margins are represented by 6 tall bars with arrows. In this demos starting position only 3 margin bars create vertical space (the other 3 are "collapsed"). Note that e-1 margin top "collapses" through two levels of parents and pushes on the top of the grey dashed frame:
Example 2 ↑
Example 2 has a DOM structure like this:
<div class="a">
<div class="b">
<div class="c">
</div>
</div>
</div>
This example shows top margin collapsing on nested elements. Collapsing can be prevented by text elements taking up vertical space between two top margins (the top element boundaries no longer touch so margin collapsing is not activated). The same rules apply to bottom margin collapsing.