CSS 盒模型:为什么 content-box 和 border-box 的实际宽度不同
CSS 盒模型用内容、内边距、边框和外边距描述盒子的尺寸和间距。同样设置 width: 240px 时,content-box 会把内边距和边框加在内容宽度之外,而 border-box 通常把它们算在 240px 以内。
盒子的四个区域
从内容向外依次是内边距、边框和外边距。背景默认绘制到边框后面,可以用 background-clip 修改这个范围。元素自己的背景不会绘制到外边距。 CSS Box Model · The Box Model
| 区域 | 作用 |
|---|---|
| 内容 | 放置文字和图像的空间 width |
| 内边距 | 内容与边框之间的空间 padding |
| 边框 | 围住内容和内边距 border |
| 外边距 | 边框外用来分隔盒子的空间 margin |
计算 content-box 和 border-box 的宽度
在 content-box 中,width 指内容宽度。下方盒子的左右内边距各为 20px,边框各为 8px,因此边框外沿之间的宽度是 240 + 2 × 20 + 2 × 8 = 296px。
.box {
box-sizing: content-box;
width: 240px;
padding: 20px;
border: 8px solid #536d88;
}
采用 border-box 时,本例的边框盒宽 240px,内容宽度为 240 - 40 - 16 = 184px。两种模式都不把外边距计入指定宽度。初始值为 content-box,但浏览器默认样式可能为某些表单控件指定其他值。 CSS Box Sizing · box-sizing
比较两个 width 相同的盒子
将代码保存为 box-model.html,然后用浏览器打开。上方的盒子使用 content-box,下方使用 border-box。宽度、内边距、边框和外边距的声明相同。窗口很窄时,可以在比较区域内横向滚动。
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>比较盒模型尺寸</title>
<style>
body {
margin: 0;
color: #243449;
background: #eef2f6;
font-family: system-ui, sans-serif;
line-height: 1.5;
}
main { max-width: 640px; margin: 24px auto; padding: 0 16px; }
h1 { font-size: 26px; }
.stage {
display: flow-root;
overflow-x: auto;
border: 1px dashed #8498ad;
background: #dfe7ef;
}
.box {
width: 240px;
margin: 16px;
padding: 20px;
border: 8px solid #536d88;
background: #fff4d9;
}
.content-box { box-sizing: content-box; }
.border-box { box-sizing: border-box; }
</style>
</head>
<body>
<main>
<h1>比较盒子尺寸</h1>
<p>两个盒子均指定 240px 宽度。</p>
<div class="stage">
<div class="box content-box">content-box</div>
<div class="box border-box">border-box</div>
</div>
<p>在开发者工具中检查内容、内边距、边框和外边距。</p>
</main>
</body>
</html>
只将共用内边距从 20px 改为 30px。上方盒子的边框盒从 296px 扩大到 316px。下方仍宽 240px,但内容宽度从 184px 减至 164px。比较后将内边距恢复为 20px。
在开发者工具中读取尺寸
右击第一个盒子并选择检查。在计算后的盒模型中找到 240px 的内容宽度、两边各 20px 的内边距和各 8px 的边框。选中第二个盒子时,内容宽度为 184px。两个盒子的边框外都有 16px 的外边距。若只在开发者工具里做了改动,可以刷新恢复。
外边距折叠与内容溢出
在普通块级布局中,相邻的正垂直外边距可能折叠。示例中两个盒子的外边距均为 16px,盒子之间的间隔也是 16px。Grid 和 Flexbox 项目的外边距不会以同样方式折叠。 CSS 2.2 · Collapsing Margins
在 border-box 模式下,内容宽度最小为零,因此内边距与边框的总宽度仍可能超过指定值。保留示例其他设置并把宽度改为 40px,盒子至少仍宽 56px。对于长单词或大图的溢出,需要另行设置换行或尺寸上限。




