CSSMedium
What is margin collapsing and how do you prevent it?
By FrontendPro Editorial Team Updated 8/7/2026
#css#layout#box-model
Answer
Adjacent vertical margins merge into the largest one instead of adding up.
css
.a { margin-bottom: 20px; }
.b { margin-top: 30px; }
/* gap = 30px, not 50px */
Three cases: adjacent siblings, parent–first/last child, and empty blocks collapsing through themselves.
Prevent it by creating a BFC or adding a boundary on the parent: display: flow-root, overflow: auto, a bit of padding/border, or use flex/grid (their children never collapse).
Most pragmatic: space things with flex/grid gap and the problem disappears.
