Introduction
The CSS Box Model explains how every HTML element is structured: content, padding, border, and margin. Understanding this fully is essential for proper layouts, spacing, and design.
1. The Four Layers
- Content — text or images inside
- Padding — space around content
- Border — line around padding
- Margin — space outside the element
2. Example Box
.box {
width: 200px;
padding: 20px;
border: 4px solid #64b5f6;
margin: 30px;
}
3. Total Rendered Width
Without box-sizing, width = content + padding + border.
total width = width + left padding + right padding + left border + right border
4. The Fix: box-sizing: border-box
* {
box-sizing: border-box;
}
Now width includes padding + border automatically. This is the modern default for all frameworks.
5. Padding Examples
padding: 20px;
padding: 10px 30px;
padding: 5px 10px 15px 20px;
6. Margin Examples
margin: 20px;
margin: 10px auto; /* center */
margin: 5px 10px 20px 0;
7. Border Examples
border: 2px solid #64b5f6;
border-radius: 10px;
border-top: 4px dashed red;
8. Margin Collapse (Important!)
Adjacent vertical margins collapse into one margin.
.a { margin-bottom: 30px; }
.b { margin-top: 50px; }
/* Resulting gap = 50px, not 80px */
9. Inline vs Block vs Inline-Block
display: inline; /* cannot set width/height fully */
display: block; /* full width */
display: inline-block; /* inline + custom size */
10. Overflow Control
overflow: hidden;
overflow: scroll;
overflow: auto;
11. Using Outline (No Effect on Box Size)
outline: 2px solid #90caf9;
12. Visual Debug Trick
* {
outline: 1px solid red;
}
13. Centering a Box
.box {
width: 300px;
margin: 0 auto;
}
14. Content-Box vs Border-Box
box-sizing: content-box; /* default, not recommended */
box-sizing: border-box; /* modern standard */
15. Summary
- The box model has content → padding → border → margin
box-sizing: border-boxsimplifies layouts- Padding/border increase element size unless using border-box
- Vertical margins can collapse
- Use outlines for debugging layouts
- Margins control spacing outside boxes; padding controls inside space