Box Model: CSS Margin Collapsing

Margin collapsing refers to the fact that when two vertical margins meet, they form a single margin.

The height of the merged margin is equal to the larger of the two margins that are merging.

Margin collapsing

Margin collapsing (stacking) is a relatively simple concept. However, in practice, it can cause a lot of confusion when laying out web pages.

In simple terms, margin collapsing refers to the fact that when two vertical margins meet, they form a single margin. The height of the merged margin is equal to the larger of the two margins that are merging.

When an element appears above another element, the bottom outer margin of the first element and the top outer margin of the second element will merge. Please see the following figure:

CSS Margin Collapsing Example 1

Try it yourself

When an element is contained within another element (assuming there is no padding or border to separate the outer margins), their top and/or bottom outer margins will also merge. Please see the following figure:

CSS Margin Collapsing Example 2

Try it yourself

Although it may seem strange, the outer margin can even merge with itself.

Suppose there is an empty element with an outer margin but no border or padding. In this case, the top outer margin and the bottom outer margin touch each other and merge together:

CSS Margin Collapsing Example 3

If this margin encounters the margin of another element, it will also collapse:

CSS Margin Collapsing Example 4

This is why a series of paragraph elements occupy a very small space, because all their margins are merged together to form a small margin.

At first glance, margin collapsing may seem a bit strange, but in fact, it is meaningful. Taking a typical text page composed of several paragraphs as an example, the space above the first paragraph is equal to the paragraph's top margin. If there is no margin collapsing, the margins between subsequent paragraphs will be the sum of the adjacent top and bottom margins. This means that the space between paragraphs is twice the distance from the top of the page. If margin collapsing occurs, the top and bottom margins between paragraphs will merge together, so the distances are consistent.

The Actual Significance of CSS Margin Collapsing

Note:Only the vertical margins of block boxes in the normal document flow will collapse. The margins between inline boxes, floating boxes, or absolutely positioned elements will not collapse.