框模型:CSS 外边距合并

外边距合并指的是,当两个垂直外边距相遇时,它们将形成一个外边距。

合并后的外边距的高度等于两个发生合并的外边距的高度中的较大者。

外边距合并

外边距合并(叠加)是一个相当简单的概念。但是,在实践中对网页进行布局时,它会造成许多混淆。

简单地说,外边距合并指的是,当两个垂直外边距相遇时,它们将形成一个外边距。合并后的外边距的高度等于两个发生合并的外边距的高度中的较大者。

当一个元素出现在另一个元素上面时,第一个元素的下外边距与第二个元素的上外边距会发生合并。请看下图:

ຄວາມຍິງ CSS ການປະສົມກັບກາງສຽງບອກທີ 1

亲自试一试

当一个元素包含在另一个元素中时(假设没有内边距或边框把外边距分隔开),它们的上和/或下外边距也会发生合并。请看下图:

ຄວາມຍິງ CSS ການປະສົມກັບກາງສຽງບອກທີ 2

亲自试一试

尽管看上去有些奇怪,但是外边距甚至可以与自身发生合并。

假设有一个空元素,它有外边距,但是没有边框或填充。在这种情况下,上外边距与下外边距就碰到了一起,它们会发生合并:

ຄວາມຍິງ CSS ການປະສົມກັບກາງສຽງບອກທີ 3

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

ຄວາມຍິງ CSS ການປະສົມກັບກາງສຽງບອກທີ 4

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

Margin collapse may seem strange at first glance, but in fact, it is meaningful. Take a typical text page consisting 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 collapse, the margin between subsequent paragraphs will be the sum of the adjacent top and bottom margins. This means that the space between paragraphs is twice the top of the page. If margin collapse occurs, the top and bottom margins between paragraphs are merged together, so the distances are consistent.

ຄວາມຍິງຂອງການປະສົມກັບກາງສຽງ CSS

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