box-sizing controls what the width and height properties actually measure. The default (content-box) measures only the content; makes them include padding and border.
box-sizing controls what the width and height properties actually measure. The default (content-box) measures only the content; makes them include padding and border.
border-box.box {
box-sizing: content-box; /* the default */
width: 200px;
padding: 20px;
border: 5px solid;
}
/* Rendered width = 200 + 2×20 + 2×5 = 250px ← bigger than you asked for! */
With content-box, padding and border are added on top of width, so the element ends up wider than the number you set. This breaks layouts: a width: 50% box with padding overflows its 50%.
.box {
box-sizing: border-box;
width: 200px;
padding: 20px;
border: 5px solid;
}
/* Rendered width = 200px TOTAL. Content shrinks to 150px to make room. */
With border-box, width is the final rendered width — padding and border are subtracted from the inside. The number you set is the size you get, which is far more intuitive.
*, *::before, *::after {
box-sizing: border-box;
}
Almost every modern stylesheet, framework, and reset applies this globally. It makes sizing predictable: width: 50% + padding stays exactly 50% wide, two width: 50% boxes sit side by side without overflowing, etc.
border-box removes the single most common source of layout-math headaches — having to mentally add padding and border to every width.
Setting it globally is considered a best-practice default, because "the width I set is the width I get" is how you naturally expect sizing to work.
A library of IT interview questions with detailed answers — from Junior to Senior.
Donate