全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-16 8 分钟 ✍️ juanwangdev

CSS外边距折叠

外边距折叠(Margin Collapse)是CSS的特性,相邻的垂直外边距会合并成一个。

发生条件

  • 相邻块级元素之间
  • 父子块级元素之间
  • 空块级元素自身

相邻兄弟元素折叠

CSS
.box1 {
  margin-bottom: 30px;
}

.box2 {
  margin-top: 20px;
}

/* 实际间距 = max(30px, 20px) = 30px */

两个 margin 取较大值,不是相加。

父子元素折叠

CSS
.parent {
  background: #eee;
}

.child {
  margin-top: 30px;
}

/* 父元素随子元素一起"塌陷" */

父子 margin-top 或 margin-bottom 会发生折叠。

解决父子折叠

CSS
/* 方法1:父元素添加边框 */
.parent {
  border-top: 1px solid transparent;
}

/* 方法2:父元素添加 padding */
.parent {
  padding-top: 1px;
}

/* 方法3:创建 BFC */
.parent {
  overflow: hidden;
  /* 或 */
  display: flow-root;
}

/* 方法4:父元素设置 position */
.parent {
  position: absolute;
}

空元素自身折叠

CSS
.empty {
  margin-top: 30px;
  margin-bottom: 20px;
  /* 没有内容、边框、内边距 */
}

/* 实际占用高度 = max(30px, 20px) = 30px */

不发生折叠的情况

情况说明
水平方向水平 margin 从不折叠
BFC 容器触发 BFC 的元素不与子元素折叠
浮动元素浮动元素的 margin 不折叠
绝对定位position: absolute/fixed
行内块display: inline-block
flex/grid 子项弹性或网格布局子元素

注意:外边距折叠只发生在垂直方向,水平方向不会折叠。

要点总结

  • 垂直相邻 margin 取较大值合并
  • 父子折叠可通过 BFC 或边框解决
  • 水平方向 margin 不会折叠
  • flex/grid 布局中不存在外边距折叠

存放路径:articles/CSS/入门/CSS盒模型/CSS外边距折叠.md

📝 发现内容有误?点击此处直接编辑

← 上一篇 CSS padding属性
下一篇 → CSS盒模型概念
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库