Box Model: CSS Margin Collapsing
- Previous Page CSS Margins
- Next Page Overview of CSS Positioning
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:

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:

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:

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

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.

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.
- Previous Page CSS Margins
- Next Page Overview of CSS Positioning