Margins collapse when two or more block-axis margins are adjoining: both belong to in-flow block-level boxes in the same block formatting context, and no line box, padding, border or clearance separates them. They then combine into one margin. Horizontal margins never collapse (in vertical writing modes the block axis is horizontal, so those do).
Three situations make margins adjoin:
- Adjacent siblings. One block's
margin-bottomand the next one'smargin-top. - Parent and first or last child. A child's
margin-topcollapses with its parent's when the parent has no top padding or border. The bottom case also needs the parent's height to beauto. This is the surprise one: the child's margin appears outside the parent, pushing the parent down. - An empty block. With no content, padding, border or height, its own top and bottom margins collapse together, and can collapse with its neighbours through it.
The arithmetic: take the largest positive margin and add the most negative one. 30px and 20px give 30px; 30px and -10px give 20px; -30px and -10px give -30px.
To stop it, separate the margins or change the layout:
paddingorborderon the parent (even1px);- make the parent a BFC root:
display: flow-root. A BFC's children never collapse with it; - use flex or grid. Their items never collapse with each other or with the container, so
gapor margins add up; clear, or inline content (text,<br>) between the margins.
Floats, absolutely positioned boxes and inline-blocks never collapse their margins at all. And the root element's margins don't collapse.