Prejsť na hlavný obsah
Frontend je bezplatný bonus na CodeMentor AI — hlavným produktom je Python. Zaregistruj sa a ulož si pokrok a odomkni všetkých 299 Frontend lekcií + 1,100+ Python lekcií.Zaregistruj sa — zdarma
← 🎨 CSS as a design system·Modul B1 · Lekcia 7
ÚlohaTwo 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.

Kolaps marže (a ako sa vyhnúť prekvapeniu)

75 XP7 minFREE
Teória

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 karty
Živý náhľad
← PredchádzajúcaĎalšia lekcia →

Jeden tip k Pythonu alebo webu denne — e-mailom

Krátke, ručne písané, žiadny spam. Odhlásiť jedným klikom.