CSS-marginalitetssammanslagning

Margin collapsing refers to the formation of a margin when two vertical margins meet.

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

Margin collapsing

Margin collapsing (叠加) is a relatively simple concept. However, in practice, it can cause much confusion when laying out web pages.

In simple terms, margin collapsing refers to the formation of a margin when two vertical margins meet. The height of the merged margin is equal to the larger of the two margins that are collapsed.

When an element appears above another element, the bottom margin of the first element and the top margin of the second element will collapse. See the following figure:

Exempel på CSS marginalitetssammanslagning 1

Try it yourself

When an element is contained within another element (assuming there are no padding or borders to separate the margins), their top and/or bottom margins will also collapse. See the following figure:

Exempel på CSS marginalitetssammanslagning 2

Try it yourself

Although it may seem a bit strange, margins can even collapse with themselves.

Suppose there is an empty element that has a margin but no border or padding. In this case, the top margin and the bottom margin meet each other, and they will collapse:

Exempel på CSS marginalitetssammanslagning 3

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

Exempel på CSS marginalitetssammanslagning 4

This is why a series of paragraph elements occupy such a small space, because all their margins are merged into a small margin.

At first glance, margin collapsing may seem a bit strange, but in fact, it is meaningful. Take a typical text page composed of several paragraphs as an example. The space above the first paragraph is equal to the top margin of the paragraph. If there is no margin collapsing, the margins between all 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 are merged together, making the distances consistent.

Det praktiska betydelsen av CSS marginalitetssammanslagning

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

All CSS margin properties

属性 描述
Egenskap Beskrivning
margin Används för att ställa in marginal egenskaper i en enda deklaration.
margin-left Ställ in elementets vänstra ytterliggörande marginal.
margin-right Ställ in elementets högra ytterliggörande marginal.
margin-top Ställ in elementets övre ytterliggörande marginal.