liveBook · Manning

Collapsing margin

As explained in Acing the Frontend Interview

Margin collapsing is the CSS layout behavior in which adjoining vertical margins combine into a single effective margin instead of being added.

Collapsing margin is a CSS layout behavior in which adjoining vertical margins combine instead of adding together. It can explain why the gap between elements is smaller than their declared margins suggest; horizontal margins do not collapse. section 2.2

A spacing question

An element has a 50px bottom margin, and its next sibling has a 30px top margin. Why is the gap 50px, not 80px? Their adjacent vertical margins collapse into one effective margin. section 2.2

Check for collapse between adjacent siblings, between a parent and child with no separating padding, border, or content, and in empty blocks. To prevent parent–child collapse, add padding or a border, or use non-visible overflow. Margins do not collapse in flex or grid containers. When debugging, identify which margins meet before changing their values. section 2.2

How Acing the Frontend Interview covers it

How deep it goes
Explains where vertical margins collapse, the resulting gap, and ways to prevent collapse without exploring browser internals.
Examples
Compares a 50px bottom margin with a 30px top margin to show a 50px gap rather than 80px.
What it assumes
Assumes familiarity with CSS margins and element layout.
What you can do after
Diagnose/debug unexpected spacing and choose layout rules that prevent unwanted collapse.
How it connects
Connects margin collapsing to the CSS box model, padding, borders, overflow, Flexbox, and Grid.

Also explained in

Compare how 2 books explain collapsing margin →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Acing the Frontend Interview. The section links point to the parts of the book it draws on.