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.