How to Prevent CSS Margin Collapsing?

Margin collapsing occurs when the vertical margins of adjacent block elements combine into a single margin, often causing unexpected layout behavior. While this is standard CSS specification behavior for block-level elements in normal flow, it can be deliberately prevented using several modern and traditional CSS techniques. This guide covers the most effective methods to stop margin collapsing, ranging from changing display contexts to utilizing padding, borders, and modern layout modules.

Use Flexbox or CSS Grid

The most robust and modern way to prevent margin collapsing is to switch the parent container's layout context to Flexbox or CSS Grid. Margins never collapse between flex items or grid items.

Establish a New Block Formatting Context (BFC)

Margins never collapse across the boundary of a Block Formatting Context. You can force a parent element or wrapper to establish an independent BFC using several CSS properties:

Add Padding or Borders to the Parent

When a child element's margin collapses through its parent (known as parent-child margin collapsing), adding even a minimal physical separation stops the collapse:

Change the Display Property of the Elements

Margin collapsing only applies to block-level elements in normal flow. Changing how an element is rendered will prevent it from participating in margin collapse: