Перейти к основному содержимому
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 или веб-разработке — каждый день в почте

Коротко, без воды, без спама. Отписаться — в один клик.