Box Model Review
Review the CSS Box Model — content, padding, border, and margin — and how it affects element sizing.
Box Model Review
Before we dive into positioning, we need to understand the CSS Box Model — because every element on the page is a box, and positioning is all about placing those boxes.
The Four Layers
Every HTML element is wrapped in a box made up of four layers:
┌─────────────── Margin ──────────────┐
│ ┌─────────── Border ──────────┐ │
│ │ ┌─────── Padding ──────┐ │ │
│ │ │ │ │ │
│ │ │ Content │ │ │
│ │ │ │ │ │
│ │ └──────────────────────┘ │ │
│ └─────────────────────────────┘ │
└─────────────────────────────────────┘
| Layer | What It Is | CSS Property |
|---|---|---|
| Content | The actual text, image, or child elements | width, height |
| Padding | Space between content and border | padding |
| Border | A line around the padding | border |
| Margin | Space outside the border (between elements) | margin |
The Sizing Problem
By default, width and height only set the content size. Padding and border are added on top:
.box {
width: 200px;
padding: 20px;
border: 5px solid #333;
}
/* Actual rendered width = 200 + 20 + 20 + 5 + 5 = 250px */
box-sizing: border-box
The fix is box-sizing: border-box, which makes width include padding and border:
* {
box-sizing: border-box;
}
.box {
width: 200px;
padding: 20px;
border: 5px solid #333;
}
/* Actual rendered width = 200px (padding and border fit inside) */
This is considered a best practice — most developers apply it to all elements with the universal selector *.
Margin Collapsing
When two vertical margins meet, they collapse — the larger margin wins instead of both being added:
.box-a { margin-bottom: 30px; }
.box-b { margin-top: 20px; }
/* Actual space between them = 30px (not 50px) */
This only happens with vertical margins, not horizontal.
Inspecting the Box Model
You can visualize the box model in your browser's Developer Tools:
- Right-click an element → Inspect
- In the Computed tab, you'll see a diagram of the box model
- Hover over the element to see the content (blue), padding (green), border (yellow), and margin (orange) highlighted
Key Takeaways
- Every element is a box with content, padding, border, and margin
- Use
box-sizing: border-boxso width includes padding and border - Vertical margins collapse — the larger one wins
- Use DevTools to visualize and debug the box model