HTML & CSS82 min total · 18 parts
CSS Fundamentals: The Box Model, Specificity, Positioning, and Layout
Part 4 of 18 · ~2 min
Margin Collapsing
The category page also has a "You might also like" section beneath the grid, and on a narrow phone screen it's just a plain stack of cards, one per row, each with a comfortable margin around it:
.card {
margin: 16px;
}
Stack two of these and measure the gap between them. It's not 32px. It's 16px.
That's margin collapsing: when two vertical margins meet with nothing between them, they don't add up — the larger one simply absorbs the smaller one and the gap is whichever value was bigger.
.card h3 { margin-bottom: 24px; }
.card .price { margin-top: 8px; }
/* the gap between the title and the price is 24px, not 32px */
A short, exact list of when this actually happens:
- This is strictly a vertical-margin, block-level, normal-flow phenomenon — margins never collapse along the horizontal axis, under any circumstance.
- It happens between adjacent siblings, and a second, less obvious case: a parent and its own leading or trailing child, whenever there's genuinely nothing between them — no padding, no border, not even a stray character of text. That second case is the one that ambushes people: wrap the card in a
<section>and give the section amargin-top, and with nothing else inside the section sitting above the card, that margin escapes straight through the parent and shoves the whole section down the page rather than opening up room inside it. - Flex and Grid containers opt their children out of this mechanism entirely, and so does any element that starts its own block formatting context —
overflow: hidden,display: flow-root, or simply being lifted out of flow via absolute positioning all qualify. That's part of why switching a stack over to one of the newer layout modes tends to make its spacing feel less like guesswork. - Two negative margins collapse to whichever one is furthest from zero. A positive paired with a negative doesn't collapse in the usual sense at all — the two are summed algebraically, so the negative value quietly cancels out part of the positive one.
The practical fallout for the card: stacking .card elements with margin: 16px each does not reliably get you 32px of breathing room between them, and "reliably" is doing real work in that sentence, because it depends on exactly what's adjacent to what. Chapter 11 replaces this stack with a Flexbox column using gap instead of margin specifically to make this stop being a question — gap never collapses, and it only ever describes the space between items, never at the ends.