box-sizing

解释 content-box 与 border-box 如何改变 width/height 的含义,以及为何全局 border-box 成为工程默认。

#type / concept #status / growing #tech / dev / frontend #resource / css

[!info] 关联笔记

box-sizing

这个概念为什么出现

设计师说卡片宽 320px,你写 width:320px; padding:16px; border:1px,结果总宽变成 354px,栅格被撑破。box-sizing 决定 width/height 到底包含哪些盒子

[!abstract] 一句话理解 content-box 的宽高只指内容区;border-box 的宽高包含 padding 与 border,更符合多数 UI 标注习惯。

最小可运行示例

场景:两列筛选栏要对齐 320 栅格

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8" />
  <style>
    .col {
      width: 320px;
      padding: 16px;
      border: 1px solid #cbd5e1;
      display: inline-block;
      vertical-align: top;
    }
    .content { box-sizing: content-box; }
    .border { box-sizing: border-box; background: #f8fafc; }
  </style>
</head>
<body>
  <div class="col content">content-box 列</div>
  <div class="col border">border-box 列</div>
  <script>
    for (const el of document.querySelectorAll('.col')) {
      console.log(el.className, el.getBoundingClientRect().width)
    }
  </script>
</body>
</html>

期望:content-box 总宽约 354;border-box 总宽约 320。

结合场景关注点

  1. 标注给的是“边框盒子宽”时用 border-box 更省心。
  2. 百分比宽度 + padding 在 content-box 下极易溢出。
  3. 全局重置常写:
*, *::before, *::after { box-sizing: border-box; }

核心模型

width 包含
content-box(初始)仅 content
border-boxcontent + padding + border

margin 永不计入 width。

常见误区

[!warning] 常见误区:border-box 让 margin 也算进 width margin 在盒子外,不在 box-sizing 口径内。

工程实践

  • 新项目默认 border-box。
  • 维护老站时注意第三方组件假设 content-box 的情况。
  • 与 flex 子项 min-width:auto 溢出问题分开看。

本节总结

先统一尺寸口径,再谈精细布局。box-sizing 是防布局算崩的开关。

自测题

  1. padding 变大时,border-box 元素的内容区如何变化?
参考答案

在 width 固定时,padding 增大挤占 content 区域,总边框盒宽保持。

延伸阅读

资料类型支撑内容
MDN box-sizing文档定义
创建于 2025/1/1 更新于 2026/7/15