Have you heard about Hack Frontend Community?Join us on Telegram!

CSS Margin Collapsing: When and Why Margins Merge

Margin collapsing is a CSS feature where vertical margins of adjacent blocks collapse (i.e., they don't add up, but the larger one is taken).

This feature only works with vertical margins (margin-top, margin-bottom) and can cause unexpected visual effects.


Example of Margin Collapsing

<div class="block1">...</div>
<div class="block2">...</div>
.block1 {
  margin-bottom: 30px;
}

.block2 {
  margin-top: 50px;
}

What will be displayed between blocks?

50px, not 80px. Because margins collapsed (the larger one was taken).

When Does Collapsing Occur?

  • Adjacent vertically standing blocks
    • When margin-bottom of one element borders margin-top of another.
    • Only works vertically.
  • Parent and first/last child
    • If parent has no padding, border, inline content, etc.
    • Margin of first/last child collapses with parent's margin.
  • Empty blocks
    • If block is empty, top and bottom margins collapse into one.

How to Prevent Collapsing?

  • Add padding or border to parent
  • Use overflow: hidden or overflow: auto
  • Use Flexbox or Grid (they don't collapse margins)
  • Add display: flow-root to parent

Important:

Margin collapsing only works vertically and only for block elements in normal flow.

By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.