什么是盒模型
What is the Box Model
一句话:每个元素都是一个盒子, 由内到外四层:content → padding → border → margin。
真正的考点是「width 到底量的是哪一段」:
box-sizing | width: 200px 指的是 | 加上 padding: 20px 后实际占 |
|---|---|---|
content-box(默认) | 只有 content | 240px(200 + 20 × 2) |
border-box | content + padding + border | 200px,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-sizing | width: 200px means | with padding: 20px it occupies |
|---|---|---|
content-box (default) | content only | 240px (200 + 20 × 2) |
border-box | content + padding + border | 200px; 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.