The Box Model
20 min read
Box Modelbox-sizingMargin CollapsingDisplay PropertyContent Box vs Border Box
The Foundation of Every Element on the Web
Every single element in CSS is a rectangular box. Understanding how the browser calculates the size of that box is the single most important CSS concept you will ever learn.
The Four Layers
| Layer | What It Is | Controlled By |
|---|---|---|
| Content | The actual text, image, or child elements | width, height |
| Padding | Space between content and border (inside the box) | padding |
| Border | The visible edge of the box | border |
| Margin | Space between this box and neighboring boxes (outside) | margin |
The box-sizing Problem
By default, CSS uses box-sizing: content-box. This means width: 300px only sets the content width. Padding and border are added on top, making the actual rendered width larger than 300px.
The fix that every modern project uses:
*, *::before, *::after {
box-sizing: border-box;
}With border-box, the width includes content + padding + border. This is how humans expect sizing to work.
Margin Collapsing
One of CSS's most confusing behaviors: when two vertical margins touch, they collapse into one (the larger value wins).
| Scenario | Element A margin-bottom | Element B margin-top | Actual Gap |
|---|---|---|---|
| Both positive | 30px | 20px | 30px (larger wins) |
| One negative | 30px | -10px | 20px (sum) |
| Both negative | -30px | -20px | -30px (more negative wins) |
Margins do NOT collapse in Flexbox, Grid, or when an element has overflow: hidden.
The display Property
| Value | Behavior | Width | Margin/Padding |
|---|---|---|---|
block | Takes full width, starts on new line | 100% of parent | All directions work |
inline | Flows with text, no line break | Content only | Horizontal only |
inline-block | Flows inline but respects box model | Content or set | All directions work |
none | Removed from layout entirely | N/A | N/A |