CodeOath
← All posts
HTML & CSS70 min total · 18 parts

CSS Fundamentals: The Box Model, Specificity, Positioning, and Layout

Contents — Part 4 of 18: Margin Collapsing
Part 4 of 18 · ~1 min

Margin Collapsing

The other box-model surprise worth knowing well: when two vertical margins meet, they don't add together — the larger one wins.

.first { margin-bottom: 30px; }
.second { margin-top: 20px; }
/* the gap between .first and .second is 30px, not 50px */

A few rules about exactly when this happens:

  • It only applies to vertical margins of block-level elements in normal flow — horizontal margins never collapse.
  • It happens between adjacent siblings (one element's bottom margin meeting the next one's top margin), and also between a parent and its first/last child if there's no padding, border, or content separating them — which is why a <div> wrapping a <h1> with margin-top can appear to "push the wrapper down" instead of adding space inside it.
  • It does not happen inside a Flexbox or Grid container, or for elements that establish a new block formatting context (like overflow: hidden, display: flow-root, or absolutely positioned elements) — one more reason those layout modes feel more predictable than plain block flow.
  • If both margins are negative, the most negative one wins; if one is positive and one negative, they're added together (effectively subtracted).

The practical fallout: don't assume stacking two elements with margin: 20px each gives you 40px of gap between them — measure, or reach for Flexbox/Grid with gap (covered later), which never collapses and is far easier to reason about.