CSS-Margenkompilierung

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

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

Margin collapsing

Margin collapsing (stacking) 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 collapsed margin is equal to the larger of the two margins that are collapsing.

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 diagram:

Beispiel für die Kompilierung von CSS-Margen

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 diagram:

Beispiel für die Kompilierung von CSS-Margen 2

Try it yourself

Even though it may seem strange, margins can even collapse with themselves.

Assume there is an empty element with margins but no border or padding. In this case, the top and bottom margins meet each other, and they will collapse:

Beispiel für die Kompilierung von CSS-Margen 3

If this margin encounters another element's margin, it will also collapse:

Beispiel für die Kompilierung von CSS-Margen 4

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

At first glance, margin collapsing may seem strange, but in fact, it makes sense. 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 were no margin collapsing, the margins between all subsequent paragraphs would be the sum of the adjacent top and bottom margins. This means that the space between paragraphs would be twice the distance from the top of the page. If margin collapsing occurs, the top and bottom margins between paragraphs would collapse together, resulting in consistent spacing throughout.

Die tatsächliche Bedeutung der CSS-Margen

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

All CSS margin properties

Eigenschaft Beschreibung
margin Kurzformular zur Angabe der Außenmarge-Attribute in einer Anweisung.
margin-bottom Setzen Sie die untere Außenmarge des Elements.
margin-left Setzen Sie die linke Außenmarge des Elements.
margin-right Setzen Sie die rechte Außenmarge des Elements.
margin-top Setzen Sie die obere Außenmarge des Elements.