Remember the box model problem? You set a width of 200px, add padding and border, and suddenly your element is bigger than you expected. box-sizing fixes that.
content-box (The Default)
By default, the width you set only applies to the content area. Padding and border are added on top:
.box {
box-sizing: content-box;
width: 200px;
padding: 20px;
border: 2px solid black;
/* total width = 200 + 20 + 20 + 2 + 2 = 244px */
}
Try it Yourself โ
This is the default behavior. It is also the reason many beginners get frustrated when layouts break.
border-box (The Savior)
When you set box-sizing: border-box, the padding and border are included in the width. A 200px box stays 200px, no matter what:
.box {
box-sizing: border-box;
width: 200px;
padding: 20px;
border: 2px solid black;
/* total width = 200px (padding and border are inside) */
}
The padding and border push the content inward instead of outward. The box takes up exactly the space you told it to.
Why border-box Wins
Almost every modern CSS framework and reset uses border-box as the default. It makes sizing predictable and layouts easier to reason about.
* {
box-sizing: border-box;
}
This one line, added to the top of your stylesheet, applies border-box to every single element. Many developers call it the first line of any new project.
Once you switch to border-box, you stop doing mental math every time you add padding. Your widths mean what they say.