The concept of margin collapse is foundational to an understanding of the box model in CSS, but it is actually quite complex and potentially confusing. The spec describing how margin collapse works is thorough but difficult to understand. This article is an attempt to give some visual examples to the concepts from the specs.

The basic idea behind margin collapse is that if two margins are adjoining, they will collapse into one margin, which will have the greater of the two margin values (it will be the more negative of the margins if both margins are negative).

What makes margins adjoining?

The key to understanding margin collapse is understanding when two margins are adjoining. Here are the basic situations:

Sibling Elements

Sibling element margin collapse
The bottom margin of an element collapses with the top margin of its proceeding sibling.

Child Elements

First child element margin collapse
The top margin of an element collapses with the top margin of its first child element.
Last child element margin collapse
The bottom margin of an element collapses with the bottom margin of its last child element.

An Element’s Own Top and Bottom Margins

Top and bottom margin collapse
The top and bottom margins of an element collapse if the element has no height, padding, or border and all of its children elements’ margins collapse (height is represented here only for clarity).

When do margins not collapse?

There are several exceptions to the margin collapse rules. This is where things can get hard to follow. Following are some visual examples of situations where margins would not collapse. For a more complete understanding, refer to the specs.

Parent element has overflow value other than visible, is positioned absolutely, inline-block, or floated; child element margins don’t collapse
Parent element has top border or padding; parent’s top margin does not collapse with first child’s top margin
Parent element has bottom border or padding; parent’s bottom margin does not collapse with last child’s bottom margin
1. Cleared child element; top margin does not collapse with parent’s top margin; 2. Cleared sibling element; top margin does not collapse with preceding sibling’s bottom margin
Additional examples where margin collapse is prevented
The example on the right is a very strange case and potentially may be a browser bug.

Further Resources

For updated and complete information about margin collapse, see the CSS Box Model Spec.