Skip to content

CSS Margin Collapse Surprise

Quick summary

You set margin-bottom: 20px and the next element margin-top: 30px — the gap is 30px (not 50px) because margins collapse.

Why this happens

  • Adjacent block-level vertical margins collapse to the larger value

  • Parent and first/last child margins collapse through

  • Expecting margins to add like padding does

Minimal example

✗ Broken code
.a { margin-bottom: 20px; }
.b { margin-top: 30px; }
/* gap between .a and .b is 30px, not 50px */
✓ Fixed code
.a { margin-bottom: 20px; }
.b { margin-top: 30px; }
/* wrap in flex container to prevent collapse */
.container { display: flex; flex-direction: column; }

Adjacent vertical margins collapse to the larger (30px), not the sum (50px). Putting the elements in a flex column container prevents collapse so margins add up.

How to diagnose

  • Measure the actual gap in DevTools and compare with the sum of margins

  • Check if the elements are block-level and adjacent (no border/padding between)

  • Look for parent-child margin collapse through

How to fix

  • Use padding instead of margin where addition is needed

  • Add a border, padding, or overflow:hidden to prevent collapse

  • Use flexbox or grid which do not collapse margins

How to prevent

  • Use flexbox/grid for layouts to avoid margin collapse entirely

  • Prefer padding for internal spacing and margin for external

Related Resources

Related Glossary

Related Lessons

  • CSS

    Learn about the box model.

← Back to language