Margin collapsing

In normal flow, the vertical margins of adjacent blocks do not add up: they merge and only the largest one remains. It is one of the most surprising behaviours when building layouts.
  • Between siblings: a margin-bottom of 2rem followed by a margin-top of 1rem leaves 2rem, not 3rem.
  • Between parent and child: the first child’s margin-top can escape the parent if it has no border, padding or content before it.
  • It only happens with vertical margins in block flow: in flex and grid margins never collapse.
  • display: flow-root creates a new block formatting context and keeps the children’s margins inside the parent.

Example

Both children have margin: 1.5rem 0. With block the margins merge and the gap between them is 1.5rem; with flex or grid they add up and the gap doubles.

Select display:
ResultLive
html
css