CSS Box Sizing
What Is box-sizing?
The box-sizing property controls how the browser calculates an element’s final width and height.
This matters because elements often have padding and border. Without the right box-sizing, layouts can become harder to predict.
content-box vs border-box
There are two main values:
content-box(default) – width/height apply to the content only. Padding and border are added outside.border-box– width/height include content + padding + border.
Default behavior (content-box):
.box {
width: 300px;
padding: 20px;
border: 5px solid #333;
box-sizing: content-box;
}
Final rendered width becomes: 300 + 20+20 + 5+5 = 350px.
Modern behavior (border-box):
.box {
width: 300px;
padding: 20px;
border: 5px solid #333;
box-sizing: border-box;
}
Final rendered width stays: 300px. The content area shrinks to make room for padding and border.
Why border-box Is Recommended
For real layouts (cards, grids, forms), border-box makes sizing predictable. You can set widths confidently without worrying that padding/border will break your grid.
Common global reset:
*,
*::before,
*::after {
box-sizing: border-box;
}
This applies border-box to all elements and pseudo-elements, which prevents many layout bugs.
Practical Example (Grid Cards)
Here is a typical card that stays inside its grid column:
.card {
box-sizing: border-box;
width: 100%;
padding: 16px;
border: 1px solid rgba(0,0,0,.14);
border-radius: 12px;
}
With border-box, the card will not “overflow” its column when padding is added.
Summary
box-sizingcontrols how width/height are calculated.content-boxadds padding/border outside the width.border-boxincludes padding/border inside the width.- Use a global
border-boxreset for predictable layouts.