Here is the problem. You write width: 300px and add padding: 20px and a 5px border. How wide is the box?
By default, the answer is 350px. The width only describes the content. Padding and border are added on top.
The two modes
box-sizing | width: 300px means |
|---|---|
content-box (the default) | The content is 300px. Padding and border make the box bigger. |
border-box | The whole box, including padding and border, is 300px. |
<style>
div { width: 200px; padding: 20px; border: 5px solid #d94a00; margin-bottom: 10px; background: #fdebd9; }
.cb { box-sizing: content-box; }
.bb { box-sizing: border-box; }
</style>
<div class="cb">content-box: total width 250px</div>
<div class="bb">border-box: total width 200px</div>
The second box is visibly narrower, even though both say width: 200px.
Why most developers use border-box
With border-box, a box you set to width: 50% stays 50% even after you add padding. Two of them fit side by side. With content-box, adding padding pushes the pair past 100% and one drops to the next line.
The standard reset
Almost every modern stylesheet begins with:
*, *::before, *::after {
box-sizing: border-box;
}
This uses the universal selector so every element, and its generated content, follows the same rule.
A horizontal scrollbar from nowhere
width: 100% plus padding on content-box makes the element wider than its parent. If you see an unexplained horizontal scrollbar, check this first.Continue with Width and Height Calculations to practice the maths.