Skip to content

CSS 外边距合并的意外

快速摘要

你设 margin-bottom: 20px、下一元素 margin-top: 30px——间距是 30px(非 50px),因为外边距合并。

为什么发生

  • 相邻块级垂直外边距合并为较大值

  • 父元素与首/末子元素外边距穿透合并

  • 误以为外边距像内边距一样相加

最小示例

✗ 错误代码
.a { margin-bottom: 20px; }
.b { margin-top: 30px; }
/* gap between .a and .b is 30px, not 50px */
✓ 修复代码
.a { margin-bottom: 20px; }
.b { margin-top: 30px; }
/* wrap in flex container to prevent collapse */
.container { display: flex; flex-direction: column; }

相邻垂直外边距合并为较大者(30px)而非之和(50px)。把元素放入 flex 列容器可阻止合并,使外边距相加。

如何诊断

  • 在 DevTools 测量实际间距并与外边距之和对比

  • 检查元素 3 素是否块级且相邻(中间无边框/内边距)

  • 查找父子外边距穿透合并

如何修复

  • 需要相加时改用内边距

  • 加边框、内边距或 overflow:hidden 阻止合并

  • 用 flexbox 或 grid,它们不合并外边距

如何预防

  • 布局用 flexbox/grid 完全避免外边距合并

  • 内部间距用内边距,外部用外边距

相关资源

相关术语

相关课程

  • CSS

    学习盒模型。

← 返回语言