box-sizing
The box-sizing property controls what is included in an element's width and height. Content-box (default) includes only content; border-box includes padding and border. Using border-box is the modern best practice.
box-sizing Values
Value | Includes | Total Size |
|---|---|---|
content-box | Only content | width + padding + border |
border-box | Content + padding + border | width (includes all) |
CSS
/* Content-box (default) */
.element {
box-sizing: content-box;
width: 200px;
padding: 20px;
border: 2px solid #333;
/* Total width = 200 + 20 + 20 + 2 + 2 = 244px */
}
/* Border-box (recommended) */
.element {
box-sizing: border-box;
width: 200px;
padding: 20px;
border: 2px solid #333;
/* Total width = 200px (width includes all) */
}
/* Apply to all elements */
* {
box-sizing: border-box;
}Why Border-Box is Better
CSS
/* Problem with content-box */
.box {
width: 100%;
padding: 20px;
border: 1px solid #ddd;
/* Exceeds parent width! */
}
/* Solution: use border-box */
.box {
box-sizing: border-box;
width: 100%;
padding: 20px;
border: 1px solid #ddd;
/* Fits perfectly in parent */
}
/* Best practice: apply globally */
*,
*::before,
*::after {
box-sizing: border-box;
}Note
Use box-sizing: border-box universally. It makes sizing predictable and prevents overflow issues. This is the modern best practice for CSS.
Next
Border radius: [Border Radius](/css/border-radius).