All HTML elements can be considered as 'boxes'. In CSS, the term "Box Model" is used when talking about design and layout. It consists of four distinct levels: Margins, Borders, Padding, and the Content area.
Imagine your element is a framed picture. Each layer of the box model serves a specific purpose:
Surrounded by Padding, Border, and Margin.
By default, when you set the width of an element, it only applies to the content area. To get the total width of the element, you must add the padding and borders on both sides.
div {
width: 300px;
padding: 10px;
border: 5px solid gray;
margin: 20px;
}
/* Total width = 300 + 10(L) + 10(R) + 5(L) + 5(R) = 330px */
box-sizing SolutionTo keep the total width exactly what you specified, you can use box-sizing: border-box;. This automatically shrinks the content area to accommodate any padding or borders.
* {
box-sizing: border-box; /* Modern standard */
}
div {
width: 300px;
padding: 10px;
border: 5px solid gray;
}
/* Total width remains 300px */
box-sizing: border-box; in your universal selector (*) for easy responsive layouts.
box-sizing: content-box means your set width only covers the content area — padding and border add extra size on top, which can push layouts wider than expected.
border-box project-wide. Setting it per-element instead of once on * leads to inconsistent sizing behavior across a codebase as it grows.
width/height — it only affects the space between boxes, not the box itself.
Watch the box grow as each layer is added — content, then padding, then border, then margin:
Margin (outermost, transparent), border (the green frame), padding (light green), content (innermost, white) — exactly the four layers described above, visualized together.
Q: Does margin count toward an element's width?
A: No — margin is outside the box entirely. Only content, padding, and border contribute to an element's own width/height.
Q: What's the default box-sizing value?
A: content-box — width/height apply to the content area only, unless you override it with border-box.
Q: How do I check an element's total rendered size in DevTools?
A: In Chrome/Firefox DevTools, the Elements/Inspector panel's "Computed" or "Layout" tab shows a live box-model diagram with all four layers' exact pixel values. See the MDN box model guide for more.