Web development

Use border-box to simplify width calculations

Use box-sizing border-box when declared widths should include padding and borders. This makes percentage-width fields and constrained panels easier to reason about.

Worked example

HTML example · save as example.html and open in a browser

<style>
*,*::before,*::after{box-sizing:border-box}
.panel{width:100%;max-width:20rem;padding:1rem;border:2px solid #234}
input{width:100%;padding:.75rem}
</style>
<div class="panel"><label for="name">Project name</label><input id="name"></div>

How it works

The panel’s maximum width includes its horizontal padding and border. Its full-width input follows the same rule, avoiding accidental expansion beyond the content area. Pseudo-elements are included in the reset so decorative boxes follow the same sizing model.

Limits and mistakes

Border-box does not include margins and does not resolve every intrinsic sizing issue. An explicit width smaller than required padding still needs sensible design. Inspect computed dimensions when combining percentage sizes, minimum widths, and nested layouts.

Check the result

Use developer tools to inspect the panel’s rendered width and box model. Confirm the input stays inside the panel at both narrow and wide viewport sizes.

Sources

Reference documentation for the behavior used in this guide: