Margin Collapsing Explained

What Margin Collapsing Is

When two vertical margins meet - between two sibling elements, or between a parent and its first/last child - the browser does not always add them together. Instead, it can collapse them into a single margin equal to the larger of the two.

Sibling Margin Collapsing

.box-a { margin-bottom: 30px; }
.box-b { margin-top: 20px; }
/* Gap between them is 30px, not 50px */

Instead of stacking to 50px, the browser collapses the two margins and uses the larger value, 30px.

Parent-Child Margin Collapsing

This is the more surprising case: if a parent has no border, no padding and no content separating it from its first child, the child's top margin can "escape" and push the parent itself down, rather than creating space inside the parent.

.parent { background: lightblue; }
.child { margin-top: 40px; }
/* Without padding/border on .parent, the whole .parent box shifts down 40px,
   instead of 40px of space appearing above .child but inside .parent */

How to Prevent It

  • Add any padding or border to the parent, even padding-top: 1px, which stops the child's margin from escaping.
  • Set display: flow-root or overflow: hidden on the parent, which creates a new formatting context that blocks collapsing entirely.
  • Use Flexbox or Grid for the layout - margin collapsing does not happen between flex or grid items.

When Margins Do Not Collapse

Margin collapsing only affects vertical margins in normal document flow. It never applies to horizontal margins, and it does not happen for elements inside a flex or grid container - one more reason those layout modes feel more predictable than older float-based layouts.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.