Skip to main content
Practice Problems

What is margin collapsing in CSS

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

html
<div class="block1">...</div> <div class="block2">...</div>
css
.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.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems