Margin collapse explained in CSS
19 Margins that collapse
hardTwo stacked blocks, one with a bottom margin and one with a top margin. Work out the gap between them, then stop a child’s margin from escaping its parent.
Stuck? Three hints, smallest first
- 1. Adjacent vertical margins collapse: the gap is the larger of the two, not the sum.
- 2. A child’s top margin escapes through a parent that has no padding, border or new block context.
- 3.
display: flow-rootcreates that context on purpose, without the side effects ofoverflow: hidden.
<div class="a">margin-bottom: 24px</div>
<div class="b">margin-top: 16px</div>
<div class="parent">
<div class="child">My 30px top margin stays inside</div>
</div>
.a {
margin-bottom: 24px;
padding: 8px;
background: #e9ecf6;
}
.b {
margin-top: 16px; /* the gap above is 24px, not 40px */
padding: 8px;
background: #eef1fd;
}
/* flow-root establishes a new block formatting context, so the child's margin
is contained instead of poking out through the top of the parent. */
.parent {
display: flow-root;
background: #f2f3f5;
border-radius: 6px;
}
.child {
margin-top: 30px;
padding: 8px;
background: #ffd75e;
color: #17171a;
}
7 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
const bottom = Number(/margin-bottom:\s*(\d+)px/.exec(css)[1]);
const top = Number(/margin-top:\s*(\d+)px/.exec(css)[1]);
const collapsed = Math.max(bottom, top);
test('the declared margins are 24 and 16', [bottom, top], [24, 16]);
test('the gap is the larger of the two', collapsed, 24);
test('it is NOT the sum', collapsed === bottom + top, false);
test('the parent creates a block context to contain its child', /display\s*:\s*flow-root/.test(css), true);
test('overflow: hidden was not used for it, which also clips', /overflow\s*:\s*hidden/.test(css), false);
test('nor a 1px transparent border, the other old workaround', /border[^;]*transparent/.test(css), false);
test('four blocks in the markup', countTag(html, 'div'), 4);
Output
Collapsing catches everyone twice. First between siblings, where two margins produce one gap of the larger size, so tuning both is wasted effort. Then between parent and first child, where the child’s top margin passes straight through a parent that has no padding, no border and no block formatting context — the parent appears to move instead of the child. display: flow-root is the modern fix and does nothing else; overflow: hidden also works but clips content and kills sticky positioning inside, which is a lot of collateral damage for a spacing bug.