The Box Model
Every element is a box of content, padding, border, and margin.
Syntax
/* content -> padding -> border -> margin */In CSS, every element is a rectangular box made of four layers, from inside out:
- Content — the text or image.
- Padding — space inside, between content and border.
- Border — a line around the padding.
- Margin — space outside, between this box and others.
Understanding the box model is key to controlling spacing and layout.
Example
Loading editor…
Press Run to see the result.
When to use it
- A developer inspects a layout bug in DevTools and uses the box model diagram to identify that unexpected padding was pushing a column past its container width.
- A designer specifies content area sizes separately from spacing, knowing that padding adds to the total element size in the default content-box model.
- A developer explains to a junior colleague why a 200px-wide div with 20px padding appears 240px wide without box-sizing: border-box.
More examples
Visualizing the four box layers
Labels all four layers of the CSS box model on a single element to make their stacking order concrete.
.box {
width: 200px;
/* content area */
padding: 20px;
/* space inside */
border: 4px solid #2965f1;
/* line around padding */
margin: 16px;
/* space outside border */
}Total rendered width calculation
Shows that in the default content-box model the rendered width exceeds the declared width by adding padding and border.
/* Total = 200 + 20*2 + 4*2 = 248px (content-box default) */
.panel {
width: 200px;
padding: 20px;
border: 4px solid #ccc;
background-color: #eef3ff;
}DevTools-friendly box model demo
A realistic card that clearly exposes all four box model layers, making it easy to inspect in browser DevTools.
.card {
box-sizing: content-box; /* default */
width: 300px;
padding: 16px 24px;
border: 2px solid #2965f1;
margin: 24px auto;
background: #fff;
}
Discussion