What is the CSS Box Model?
Answer
The CSS Box Model is the foundation of layout in CSS. Every HTML element is represented as a rectangular box consisting of four areas: content, padding, border, and margin.
Box Model Diagram
The Four Areas
| Area | Description | Affected by |
|---|---|---|
| Content | The actual content (text, images) | width, height |
| Padding | Space between content and border | padding |
| Border | The border around padding | border, border-width |
| Margin | Space outside the border | margin |
Example
.box {
width: 200px; /* Content width */
height: 100px; /* Content height */
padding: 20px; /* All sides */
border: 5px solid black;
margin: 10px;
}
Total Size Calculation (content-box)
Total Width = width + padding-left + padding-right + border-left + border-right
Total Width = 200 + 20 + 20 + 5 + 5 = 250px
Total Height = height + padding-top + padding-bottom + border-top + border-bottom
Total Height = 100 + 20 + 20 + 5 + 5 = 150px
box-sizing Property
/* Default behavior */
.content-box {
box-sizing: content-box; /* Default */
width: 200px;
padding: 20px;
/* Total width: 240px */
}
/* Easier to work with */
.border-box {
box-sizing: border-box;
width: 200px;
padding: 20px;
/* Total width: 200px (content shrinks to 160px) */
}
/* Best practice: Apply to all elements */
*,
*::before,
*::after {
box-sizing: border-box;
}
Margin Collapsing
When vertical margins of adjacent elements touch, they collapse into a single margin (the larger one wins):
<div style="margin-bottom: 30px;">Box 1</div>
<div style="margin-top: 20px;">Box 2</div>
<!-- Space between = 30px (not 50px) -->
Margin collapsing happens:
- Between adjacent siblings
- Between parent and first/last child (if no padding/border separates them)
- On empty blocks
Inspecting in DevTools
Open DevTools → Elements → Computed tab to see the box model visualization with actual calculated values.
Key Points
- Every element is a box with content, padding, border, margin
box-sizing: border-boxmakes width/height include padding and border- Vertical margins can collapse
- Margin can be negative, padding cannot
- Use DevTools to visualize the box model