Definition
The box-sizing
CSS property defines how the width and height of an element are calculated. By default, elements use the content-box
model, where padding and border are added to the width and height. If box-sizing
is set to border-box
, padding and border are included in the element’s width and height.
For example, box-sizing: border-box;
ensures the element maintains its defined height and width, even when padding and border are added.
Syntax
.card {
box-sizing: border-box;
}
Values
-
content-box
: width/height apply only to content; padding and border are added outside (default). -
border-box
: width/height include padding and border, simplifying layout math. -
inherit
/initial
/unset
: participate in cascade explicitly.
Practical Examples
.card {
width: 18rem;
padding: 1.5rem;
border: 4px solid #0ea5e9;
}
border-box
makes declared widths more predictable when padding or border widths change.
HTML
box-sizing: content-box
Padding adds on top of the width.
box-sizing: border-box
Padding and border are included inside the width.
Code
<div class="grid gap-4 sm:grid-cols-2">
<div class="space-y-3 rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">box-sizing: content-box</p>
<div class="rounded-lg border-4 border-sky-300 bg-slate-50 p-6 text-sm text-slate-700" style="box-sizing: content-box; width: 240px;">Padding adds on top of the width.</div>
</div>
<div class="space-y-3 rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">box-sizing: border-box</p>
<div class="rounded-lg border-4 border-sky-500 bg-slate-50 p-6 text-sm text-slate-700" style="box-sizing: border-box; width: 240px;">Padding and border are included inside the width.</div>
</div>
</div>
Tips & Best Practices
- Set
box-sizing: border-box
on the*
selector orhtml
element as a project-wide baseline. - Pair with CSS variables to adjust padding without recalculating layout widths.
- Remember that replaced elements (like
<img>
) have UA styles; consider resetting them too.
Accessibility & UX Notes
Consistent sizing reduces layout shift, keeping focus indicators and interactive regions stable.
Browser Support
box-sizing
is supported in all modern browsers, including IE8+.
Related
-
width
/height
declarations that depend on the box model. -
padding
andborder
which contribute to overall size. -
outline
for focus treatments that ignore the box model.