Every element in CSS is a rectangular box made of four layers: content → padding → border → margin. Understanding how these layers affect size and spacing is essential for layout.
CSS Box Model
1) Visual Diagram
Margin
Border
Padding
Content
margin
border
padding
content (text, images, etc.)
2) How Size Is Calculated (Default: content-box)
.box {
width: 200px; /* content width only */
padding: 16px; /* adds 16px on left + right (total 32px) */
border: 2px solid #90caf9; /* adds 2px on left + right (total 4px) */
margin: 12px; /* outside spacing */
}
Final rendered width =
content width (200) + padding L/R (32) + border L/R (4) = 236px
Margin sits outside and doesn’t add to the element’s own width.
content-box (declared 200px, but renders wider due to padding/border)
3) box-sizing: border-box (Recommended)
*, *::before, *::after {
box-sizing: border-box;
}
With border-box, the declared width/height includes padding and border. This makes layouts more predictable.
border-box (declared 200px, renders exactly 200px including padding/border)
.card {
box-sizing: border-box;
width: 300px;
padding: 20px;
border: 2px solid #ccc;
}
Final width remains 300px.
4) Margin vs Padding
.outer-gap { margin: 16px; } /* space outside border */
.inner-space{ padding: 16px; } /* space inside border; expands background */
No outer margin
With outer margin (gap outside)
No padding
With padding (colored area expands)
5) Margin Collapsing (Vertical)
/* Adjacent vertical margins between blocks may collapse */
p { margin: 20px 0; }
If one paragraph has margin-bottom:20px and the next has margin-top:20px, the space between them is 20px, not 40px. Add padding or border to the parent to prevent collapsing.
Practical Checklist:
- Remember the order: content → padding → border → margin.
- Default sizing is
content-box; consider globalborder-boxfor predictable layouts. - Use margin for spacing between elements; padding for inner breathing room.
- Vertical margins may collapse; use padding/border to separate sections.
- Borders contribute to size unless using
border-box.