Codectionary / Developer documentation / CSS

Understanding Vertical Margin Collapse

Adjacent block margins can collapse into a combined margin instead of adding together.

What it is and why to use it

Adjacent block margins can collapse into a combined margin instead of adding together. Parent and child margins can also collapse in certain ordinary block layouts. Understanding this explains why a large top margin can appear to move a parent rather than create space inside it.

Common mistakes and limitations

This is about block-axis margins in the relevant block layout, not every spacing property. Flex and grid item margins do not collapse in the same way. Negative margins and empty blocks make the rules more subtle; inspect the formatting context rather than adding arbitrary spacers.

Try the example

The example pairs editable CSS with its own HTML preview. Run it, then change one declaration at a time and compare the result. Locally, put the CSS in a style element in the document head or in an external stylesheet linked from the HTML. Feature support varies by browser and version; use the linked reference and a useful fallback where needed.

HTML used by this example

<div class="panel"><p>A paragraph with internal vertical margins.</p></div><p>A following paragraph.</p>

Syntax

display: flow-root; /* one way to establish a new block formatting context */

Examples

Understanding Vertical Margin Collapse

Run the CSS against the supplied HTML, then experiment with the values.

.panel { display: flow-root; background: #dbeafe; color: #172b4d; }
.panel p { margin-block: 2rem; }
.panel + p { margin-block-start: 1rem; }
  1. The panel establishes a new block formatting context, preventing its child’s vertical margins from collapsing through its boundary.
  2. The paragraph’s margins now appear within the panel’s background.
  3. Compare by removing flow-root. This is useful for diagnosing spacing, although padding is often the clearer way to express container inset.
HTML used by this example
<div class="demo"><div class="panel"><p>A paragraph with internal vertical margins.</p></div><p>A following paragraph.</p></div>

Best practices

  • This is about block-axis margins in the relevant block layout, not every spacing property. Flex and grid item margins do not collapse in the same way. Negative margins and empty blocks make the rules more subtle; inspect the formatting context rather than adding arbitrary spacers.
  • Inspect the relevant browser reference and test the browsers used by your audience.

Runtime & versions

Web browsers. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

CSS specifications (modules)

Specifications & further reading