The box model
Content, padding, border and margin — plus collapsing margins and how sizing math really works.
Four layers per box
Every element renders as a rectangular box. From the inside out: content, padding, border, margin.
.card {
width: 300px;
padding: 16px;
border: 1px solid #ddd;
margin: 24px;
box-sizing: border-box; /* width includes padding + border */
}| Layer | Inside background? | Purpose |
|---|---|---|
| Content | Yes | Text and child boxes |
| Padding | Yes | Space between content and border |
| Border | On the edge | Visible outline |
| Margin | No | Space to neighbours — may collapse |
The sizing math
By default (content-box) a declared width applies only to the content, so the box actually occupies width + padding + border. That surprises everyone once. Switch to border-box and the declared width is the final visible width.
*, *::before, *::after { box-sizing: border-box; }Margin collapsing
Adjacent vertical margins merge into one — the larger value wins, rather than adding up. This applies between stacked siblings, and between a parent and its first/last child when there is no padding or border between them.
- Only vertical margins collapse — never horizontal ones.
- Margins do not collapse in flex or grid containers.
- Create a new formatting context (e.g.
display: flow-root,overflow: auto, padding, or border) to stop unwanted collapse.
p { margin: 0 0 16px; } /* 16px between paragraphs, not 32px */
.stack { display: flow-root; } /* stops parent/child collapsing */Debugging layout
Nothing beats seeing the boxes. DevTools shows the computed box layer-by-layer; a temporary outline is the fastest way to find unexpected overflow.
* { outline: 1px solid red; } /* temporary: never ship this */FAQ
Why is my element wider than the width I set?
content-box adds padding and border on top of your width. Set box-sizing: border-box.How do I centre a block horizontally?
margin-inline: auto with a defined width. Centre vertically with flex or grid, not with margins.Related
Last refreshed 2026-09-17.