CSS Padding and box-sizing
The box-sizing property decides whether padding and border are added to an element's declared width or included within it.
By default, the <width> and <height> you set apply only to the content area. Any padding and border you add are then placed outside that, making the element visually larger than the number you wrote. The <box-sizing> property lets you change this calculation.
content-box versus border-box
The default: content-box
<!DOCTYPE html>
<html>
<head>
<style>
.card {
box-sizing: content-box;
width: 200px;
padding: 20px;
border: 2px solid #ccc;
}
/* Rendered width = 200 + 40 + 4 = 244px */
</style>
</head>
<body>
<div class="card">Content box</div>
</body>
</html>Predictable sizing with border-box
<!DOCTYPE html>
<html>
<head>
<style>
.card {
box-sizing: border-box;
width: 200px;
padding: 20px;
border: 2px solid #ccc;
}
/* Rendered width stays exactly 200px */
</style>
</head>
<body>
<div class="card">Border box</div>
</body>
</html>A common reset
Many developers apply border-box to every element at the top of their stylesheet so that widths always behave predictably across the whole page.
Global box-sizing reset
<!DOCTYPE html>
<html>
<head>
<style>
*,
*::before,
*::after {
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="card">
<h3>Product</h3>
<p>All elements share the same box-sizing.</p>
</div>
</body>
</html>Note: border-box makes layouts far easier to reason about, especially when mixing percentages with fixed padding.