CSS margin collapsing
- Forrige side CSS margin
- Næste side CSS padding
Margin collapsing refers to the fact that when two vertical margins meet, they will form a margin.
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 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 will form a margin. 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 figure:

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:

Although it may seem a bit strange, margins can even collapse with themselves.
Suppose there is an empty element with margins but no borders or padding. In this case, the top margin and the bottom margin meet, and they will collapse:

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

This is why a series of paragraph elements take up very little space, because all their margins collapse into a small margin.
Margin collapsing may seem a bit strange at first glance, 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 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 will be twice the space at the top of the page. If margin collapsing occurs, the top and bottom margins between paragraphs will collapse together, making the distances consistent.

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
Egenskab | Beskrivelse |
---|---|
margin | Kortform for at sætte marginegenskaber i en enkelt deklaration. |
margin-bottom | Indstil elementets nederste yderside margen. |
margin-left | Indstil elementets venstre yderside margen. |
margin-right | Indstil elementets højre yderside margen. |
margin-top | Indstil elementets øverste yderside margen. |
- Forrige side CSS margin
- Næste side CSS padding