目录

CSS 外边距折叠


有时两个边距会折叠成一个边距。


外边距折叠

元素的顶部和底部边距有时会折叠成单个边距,该边距等于两个边距中最大的一个。

这不会发生在左右边缘!只有顶部和底部边距!

看下面的例子:

示例

margin折叠演示:

h1 {
  margin: 0 0 50px 0;
}

h2 {
  margin: 20px 0 0 0;
}
亲自试一试 »

在上面的示例中,<h1> 元素的下边距为 50 像素,<h2> 元素的上边距设置为 20 像素。

常识似乎表明 <h1> 和 <h2> 之间的垂直边距总计为 70 像素 (50 像素 + 20 像素)。但由于边距塌陷,实际边距最终为 50px。


通过练习测试一下

练习:

向 <h1> 元素添加 20 像素的左边距。

<style>
h1 {
  : 20px;
}
</style>

<body>
  <h1>This is a heading</h1>
  <p>This is a paragraph</p>
  <p>This is a paragraph</p>
</body>

开始练习


所有 CSS 边距属性

Property Description
margin A shorthand property for setting all the margin properties in one declaration
margin-bottom Sets the bottom margin of an element
margin-left Sets the left margin of an element
margin-right Sets the right margin of an element
margin-top Sets the top margin of an element