Margin Collapse: Vertical Margins
You'll learn why two vertical margins touching each other don't add up like you'd expect.
When you place one block element directly above or below another, their vertical margins don't combine the way you might think. Instead of adding together (like 20px + 30px = 50px), they collapse into a single margin equal to whichever is larger.
How It Works
Imagine two magnets with the same pole facing each other — they don't stack their repelling forces; they simply push apart to the stronger force's distance. Similarly, when a bottom margin meets a top margin, CSS only applies the larger of the two.
Example scenario:
- A paragraph has
margin-bottom: 20px - The next paragraph has
margin-top: 30px - The actual space between them? 30px (not 50px!)
When Margins Collapse
This happens when:
- Adjacent block elements sit vertically next to each other
- A parent's margin touches its first/last child's margin (no padding or border separating them)
- Empty blocks with only margins
When They Don't Collapse
- Horizontal (left/right) margins never collapse
- Elements with padding or borders between their margins
- Floated or absolutely positioned elements
- Inline or inline-block elements
Key Takeaway: Adjacent vertical margins collapse to the larger value, not their sum. Predict spacing by identifying which margin wins, and remember horizontal margins always add normally.