Margin collapsing means two vertical margins merge into one. Only vertical margins of block-level boxes in normal flow collapse. Normal flow is the default layout, with no flex, grid, floats or absolute positioning.
It happens in three places:
- between adjacent siblings
- between a parent and its first or last child, when nothing separates them
- through empty blocks, whose own top and bottom margins merge
The result is the largest positive margin plus the most negative one. For example, 30px and 20px give 30px. And 30px and −10px give 20px.
The parent case is the surprising one. Say the parent has no border, no padding, no inline content and no new formatting context above its first child. Then the child's top margin merges with the parent's. The margin appears outside the parent, so the whole parent seems pushed down.
To prevent it:
- Add padding or a border to the parent.
- Create a new block formatting context, for example with
display: flow-root. A block formatting context is a separate layout area. Margins inside it don't merge with margins outside it. - Use flex or grid with
gap. Margins never collapse on flex or grid items, floats or absolutely positioned elements.
- Only vertical margins of block boxes in normal flow collapse.
- They collapse between siblings, between a parent and its first or last child, and through empty blocks.
- Parent-child collapse makes the child's margin appear outside the parent.
- Fix it with padding or a border,
display: flow-root, or flex or grid withgap.