Vai al contenuto principale
Il Frontend è un bonus gratuito su CodeMentor AI — il prodotto principale è Python. Registrati per salvare i tuoi progressi e sbloccare tutte le 299 lezioni di Frontend + 1,100+ lezioni di Python.Registrati — gratis
← 🎨 CSS as a design system·Modulo B1 · Lezione 7
CompitoTwo 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.

Crollo dei margini (e come evitare sorprese)

75 XP7 minFREE
Teoria

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 schede
Anteprima live
← PrecedenteProssima lezione →

Ricevi un consiglio Python o web al giorno — via email

Breve, scritto a mano, niente spam. Disiscriviti in un clic.