Topic 3 of 30
Box Model
Overview
Every HTML element is a rectangular box consisting of content, padding, border, and margin. Understanding the box model is the most fundamental concept for predicting layout and sizing in CSS.
Syntax
css
/* The Box Model layers (inside out):
Content → Padding → Border → Margin */
.box {
width: 300px; /* content width */
padding: 20px; /* space inside border */
border: 2px solid gold;/* the border itself */
margin: 16px; /* space outside border */
/* box-sizing: border-box makes width include padding+border */
box-sizing: border-box;
}Common Pitfalls
- Without box-sizing: border-box, adding padding to a 300px element makes it wider than 300px — a common layout bug.
- Margin collapse: adjacent vertical margins merge into one (the larger value). This is unexpected for beginners.
- Interview tip: The default box-sizing is content-box. Always set border-box in a global reset.
Real-World Example
A card component with proper box model control:
example
css
/* Global reset — always do this */
*, *::before, *::after {
box-sizing: border-box;
}
.product-card {
width: 280px;
padding: 24px;
border: 1px solid rgba(255, 215, 0, 0.3);
border-radius: 12px;
margin: 16px;
background: #1a1a1a;
}
/* Total visual width = 280px (padding included due to border-box) */
/* Space between cards = 16px * 2 = 32px */