CSS Child / The Box

Collapsing margins, the space that is not the sum of parts.

Outer space between stacked elements merges rather than adds, which is intentional and initially baffling.

Place two paragraphs one above the other. Give the first some outer space below it and the second some outer space above it. You might expect the gap between them to be the two amounts added together. It will not be. It will be the larger of the two, and the smaller simply vanishes into it. The same thing happens between a container and the first or last element inside it, where that element's outer space can escape through the container's edge and appear outside it entirely, which is the version that makes people think something is badly broken.

It is not broken, and the reasoning is typographic rather than arbitrary. In a flowing document, every heading wants a certain minimum air above it and every paragraph wants a certain air below it, and if those requirements simply added up, a heading following a paragraph would sit in a chasm while a heading following another heading sat in a slot. Merging them means each element states the minimum breathing room it needs and the document honours the largest request. The result is consistent vertical rhythm without anyone having to calculate the combinations by hand.

The practical lesson for a beginner is a habit rather than a workaround. Pick one direction and stay in it: give elements outer space below only, or above only, consistently, throughout your work. If every element pushes in the same direction, there is nothing to merge and the surprise never occurs. Better still, for things arranged as a deliberate group, do not use outer space between them at all. Modern arrangement offers a way to state the gap between siblings directly as a property of the group, which is clearer, does not merge, and is discussed later in this issue.