CSS margin collapsing

Apr 20, 2021css-conceptscss

According to CSS box model, every element in the document tree is a rectangular box made up of four areas - content, padding, border, and margin. Margin is a transparent area controlled by margin-top, margin-right, margin-bottom, margin-left, and shorthand margin.

In CSS, the adjoining margins of two or more elements (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.

Margins only collapse in the block direction. So if you are in a horizontal writing mode, only vertical margins are specified to collapse.

Following margins will not collapse

  • Margins of the root element
  • Margins of absolutely positioned or floated elements
  • Margins of Flexbox, Grid, or inline-block elements
  • Margins of elements separated by lines boxes, clearance, paddings, and borders
  • Margins of elements that establish new block formatting contexts (such as floats and elements with overflow other than visible) do not collapse with their in-flow children.

Following margins may collapse

  • Margins between adjacent siblings
  • Top and bottom margins of an empty element
  • Top margins of a parent and its first child
  • Bottom margins of a parent and its last child

Resulting collapsed margin

  • In the case of all positive margins, collapsed margin is the largest margin.
collapsed_margin = max(pm_1, pm_2,..., pm_k)
  • In the case of all negative margins, collapsed margin is the smallest (most negative) margin.
collapsed_margin = min(nm_1, nm_2, ..., nm_k)
  • In the case of mixed positive and negative margins, collapsed margin is the sum of the largest positive margin and the smallest (most negative) negative margin.
collapsed_margin = max(pm_1, pm_2, ..., pm_k) + min(nm_1, nm_2, ..., nm_l)