Skip to main content
Frontend is a free bonus on CodeMentor AI — the main product is Python. Register to save your progress and unlock all 290 Frontend lessons + 1,000+ Python lessons.Sign up — free
🎨 CSS as a design system·Module B1 · Lesson 7
TaskTwo paragraphs stacked. First has margin-bottom 30px, second has margin-top 50px. Normally they'd collapse to 50px space. Wrap both in a .section div with display: flow-root to stop the collapse — net space then becomes 30 + 50 = 80px.

Margin collapse (and how to avoid surprise)

75 XP7 minFREE
Theory

A CSS quirk that bites every junior

Two block elements stacked vertically. Both have margin. The total space between them is NOT the sum of margins — it's the LARGER of the two.

<p style="margin-bottom: 30px">First</p>
<p style="margin-top: 50px">Second</p>

Space between? 50px, not 80. The browser collapses adjacent vertical margins to whichever is bigger.

When margin collapse happens

  • Two vertically-adjacent block elements
  • The top margin of a child can collapse THROUGH the parent and become the parent's top margin (if the parent has no padding/border on top)
  • Empty blocks can collapse their own top/bottom margins together

How to STOP margin collapse

Any of these on the parent breaks the collapse:

  • padding-top: 1px (or any non-zero padding)
  • border-top: 1px solid (or any visible border)
  • overflow: hidden / overflow: auto
  • display: flow-root (modern, dedicated way)
  • display: flex or display: grid (flexbox/grid items don't collapse)
.section { display: flow-root; }   /* clean, no side effects */

Margin collapse does NOT happen with

  • Flexbox / Grid items
  • Inline-block elements
  • Horizontal margins (left/right, ever)
  • Floated elements

The takeaway

If your layout has surprising vertical spacing, suspect margin collapse first. The fix is usually adding display: flow-root to the parent or switching to flex/grid (which never collapse).

2 tabs
Live preview
PreviousNext lesson →

Get one Python or web tip a day — by email

Short, hand-written, no spam. Unsubscribe in one click.