Skip to content
AITroveRead. Build. Understand.
Make this comfortable

CSS margin collapse: explain vertical gaps before changing them

Last updated: 1 Oct 20265 min read
tutorial
BeginnerBy AITrove Editorial

In normal block flow, adjoining vertical margins can collapse into one gap. This applies to some sibling and parent-child relationships, not to flex or grid items.

When to use it

An incident report has a heading followed by a paragraph, but the measured gap is smaller than the sum of both margins. Before adding a larger number, inspect whether the margins collapsed. A border or padding between a parent and first child can separate their margins, and a grid or flex container changes the formatting context so its item margins do not collapse in the same way. None of those should be added solely to defeat a mystery; choose the layout model for the actual component. The sample gives the report section its own padding and uses one explicit heading-to-body gap. Check the first section, two adjacent sections, and the printed report where page breaks can change spacing.

css
.incident-section { padding-block: 1rem; }
.incident-section h2 { margin-block: 0 .75rem; }
.incident-section p { margin-block: 0 1rem; }
.incident-section p:last-child { margin-block-end: 0; }

Cost and verification

Margin collapse itself is ordinary browser layout, not a performance defect. The cost comes from compensating with unrelated padding or negative margins across many templates. A direct local rule is easier to reason about than a series of overrides whose values depend on source order. Inspect computed margins and the box model in developer tools when a gap changes. Negative margins can make the collapsed result more surprising, so avoid using them as a first fix. At high zoom, preserve enough separation to distinguish sections without relying on a fixed card height.

Common Mistakes

  • Do not add both sibling margins and expect their sum in block flow.
  • Do not assume flex and grid item margins collapse.
  • Do not patch a gap with a negative margin before finding its owner.

Connected lessons

css
reference
web
Storage details