Перейти до основного вмісту
Frontend — це безкоштовний бонус CodeMentor AI; основний продукт — Python. Зареєструйся, щоб зберегти прогрес і відкрити всі 299 уроків фронтенду + 1,100+ уроків Python.Зареєструватись — безкоштовно
← 🎨 CSS as a design system·Модуль B1 · Урок 7
ЗавданняTwo 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.

Падіння маржі (і як уникнути несподіванки)

75 XP7 minFREE
Теорія

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 вкладок
Живий перегляд
← НазадНаступний урок →

Отримуй одну пораду з Python чи вебу — щодня поштою

Коротко, без води, без спаму. Відписка — в один клік.