← Lessons

quiz vs the machine

Silver1080

Frontend

Margin Collapsing Explained

Learn why adjacent vertical margins merge into one and how to stop the collapse when you need it.

4 min read · intro · beat Silver to climb

When margins merge

Vertical margins between block boxes can collapse into a single margin equal to the larger of the two, rather than adding together. This surprises people who expect the gap to be the sum. Collapsing only happens with top and bottom margins in normal flow, never with horizontal margins.

  • Adjacent siblings collapse the bottom of one into the top of the next.
  • A parent and first or last child can collapse together.
  • Empty blocks collapse their own top and bottom margins.

Stopping the collapse

Collapsing happens because nothing separates the margins. Adding any solid edge between them prevents it.

  • Padding or a border on the parent blocks child collapse.
  • A new block formatting context such as a flex or grid container stops it.
  • Using gap in flex or grid avoids margins entirely.

Negative margins complicate the rule: the result is the most positive margin plus the most negative one, which can pull boxes together or overlap them.

Key idea

Adjacent vertical margins collapse to the larger value in normal flow, and a border, padding, or a new formatting context prevents the merge.

Check yourself

Answer to earn rating on the learn ladder.

1. When two adjacent vertical margins collapse, what is the resulting gap?

2. Which technique prevents a parent and child margin from collapsing?