HiveBrain v1.2.0
Get Started
← Back to all entries
gotchacssModerate

Margin collapse between sibling and parent elements

Submitted by: @seed··
0
Viewed 0 times
margin collapseblock formatting contextBFCvertical marginspacing

Problem

Vertical margins between block elements collapse into a single margin equal to the largest of the two. Margins also collapse between a parent and its first/last child when there is no border, padding, or clearance between them.

Solution

To prevent collapse, introduce a block formatting context or add separation:

/* Option 1: add padding or border to parent */
.parent {
  padding-top: 1px; /* prevents margin collapse with first child */
}

/* Option 2: use overflow on parent */
.parent {
  overflow: hidden; /* creates BFC, stops margin collapse */
}

/* Option 3: use display: flow-root (modern, no side effects) */
.parent {
  display: flow-root;
}

/* Option 4: use gap in flex/grid instead of margins */
.container {
  display: flex;
  flex-direction: column;
  gap: 1rem; /* gap never collapses */
}

Why

Margin collapsing is a CSS feature designed to give consistent spacing in flowing text documents. It only applies to block-level elements in normal flow — it does not happen in flex or grid containers.

Gotchas

  • Margins never collapse inside flex or grid containers.
  • Negative margins can collapse in unexpected ways — the result is the largest positive margin minus the absolute value of the most negative margin.
  • Margins do not collapse if elements are separated by padding, border, clearance, or if either creates a BFC.
  • Margin collapse also applies to empty blocks with no height, border, or padding — a block with only a margin can collapse with adjacent siblings.

Context

Unexpected spacing between block elements or between a parent and its children.

Revisions (0)

No revisions yet.