DrillLab
第 6 / 105 道6 / 105 · #271

什么是盒模型

What is the Box Model

先自己答,再往下看Answer it yourself first

一句话:每个元素都是一个盒子, 由内到外四层:content → padding → border → margin

真正的考点是「width 到底量的是哪一段」

box-sizingwidth: 200px 指的是加上 padding: 20px 后实际占
content-box(默认)只有 content240px(200 + 20 × 2)
border-boxcontent + padding + border200px,content 被挤到 160px

为什么现在几乎所有项目都全局改成border-box因为「我说 200 宽就是 200 宽」符合直觉。 默认那套会让你在做「三列各 33.3%」时, 一加 padding 就换行 —— 这是新手最常撞的墙。

会追问:「margin 属于盒子吗?」——border-box不包含 margin。 margin 永远在盒子外面,是「盒子之间的距离」。

还会追问 margin 折叠(margin collapse):上下相邻的两个块级元素,上面的 margin-bottom: 20px和下面的 margin-top: 30px不会得到 50px,而是 30px(取较大值)。 这也是很多人「怎么调都差一点」的原因。 Flex 和 Grid 容器的子项不发生折叠

In one line: every element is a box with four layers from the inside out: content → padding → border → margin.

What is actually being tested is “what exactly does width measure?”

box-sizingwidth: 200px meanswith padding: 20px it occupies
content-box (default)content only240px (200 + 20 × 2)
border-boxcontent + padding + border200px; content is squeezed to 160px

Why does nearly every project switch to border-box globally? Because “when I say 200 wide I mean 200 wide” matches intuition. The default makes three columns at 33.3% wrap the moment you add padding — the wall every beginner hits.

Follow-up: “Is margin part of the box?” — even border-box excludes margin. Margin is always outside; it is the distance between boxes.

They will also ask about margin collapse: two adjacent block elements with margin-bottom: 20px and margin-top: 30px give you 30px, not 50px (the larger wins). This is why spacing so often ends up “slightly off”. Flex and grid children do not collapse.

CSS全局重置示意Illustrative
1/* 几乎每个项目开头都有这三行 */
2*,
3*::before,
4*::after {
5 box-sizing: border-box;
6}
1/* Almost every project starts with these three lines */
2*,
3*::before,
4*::after {
5 box-sizing: border-box;
6}