Understanding margin collapse in CSS

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
If the parent element has an overflow value other than visible, or is positioned absolutely, inline-block, or floated, then the 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
If the parent element has a top border or padding, the parent’s top margin does not collapse with the 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
If the parent element has a bottom border or padding, the parent’s bottom margin does not collapse with the last child’s bottom margin.

Further Resources

There are some additional, more complex scenarios that prevent margin collapse that aren’t covered here. For updated and complete information about margin collapse, see the CSS Box Model Spec.

More Articles

See more articles