The CSS Box Model
Every HTML element is a rectangular box. The CSS Box Model defines four layers: content (the actual text/image), padding (space inside the border), border (the visible outline), and margin (space outside the border). Understanding this model is the key to controlling layout and spacing in CSS.
Box Model Layers
- Content — The actual text, image, or child elements. Sized with width and height
- Padding — Space between the content and the border. background-color fills this area
- Border — The visible outline around the element. Has width, style, and color
- Margin — Space outside the border. Creates distance between elements. Transparent — never has background
- Total element width = content width + left/right padding + left/right border + left/right margin
- box-sizing: border-box changes this — width includes padding and border (the modern standard)
- DevTools box model — Right-click → Inspect → see the box model diagram with exact pixel values
Box Model Code
/* Box Model visualization */
.box {
width: 300px; /* Content width */
padding: 20px; /* Space inside border */
border: 2px solid #333; /* Visible outline */
margin: 16px; /* Space outside border */
background: #f0f4f8; /* Fills content + padding */
}
/* Total rendered width WITHOUT border-box:
300 + 20+20 + 2+2 + 16+16 = 376px */
/* With border-box (recommended): */
* { box-sizing: border-box; }
.box {
width: 300px; /* Width INCLUDES padding + border */
padding: 20px; /* Subtracted from 300px */
border: 2px solid; /* Subtracted from 300px */
margin: 16px; /* Still outside */
}
/* Content area = 300 - 40 - 4 = 256px */
/* Rendered box width = 300px (predictable!) */Try It Yourself: Box Model
Tip
Always add * { box-sizing: border-box; } as the first rule in every project. This makes width and height calculations predictable — padding and borders are included inside the specified dimensions instead of being added on top.
Every element follows the box model — content + padding + border + margin
Common Mistake
Setting width: 300px then adding padding: 20px makes the element 340px wide (without border-box). This is the #1 layout bug for beginners. With box-sizing: border-box, the content shrinks to 260px so the total stays at 300px.
Practice Task
In the editor above: (1) Change the first box's padding to 40px and observe how the content area shrinks (because of border-box). (2) Remove the box-sizing: border-box line and see how the box width changes. (3) Add it back — see why it's essential!
Quick Quiz
Key Takeaways
- Every HTML element is a rectangular box.
- Content — The actual text, image, or child elements. Sized with width and height
- Padding — Space between the content and the border. background-color fills this area
- Border — The visible outline around the element. Has width, style, and color