Width, Height & box-sizing
Control element size — and fix the classic “my box is too wide” bug with one magic line.
What you will learn
- Set width, height, max-width and min-width
- Understand why padding can break widths
- Fix sizing with box-sizing: border-box
Width and height
Set size with width and height. Use max-width so an element never grows too wide on big screens, and shrinks on small ones.
<style>
.container { max-width: 400px; background: #e0e7ff; padding: 16px; margin: 0 auto; }
</style>
<div class="container">max-width: 400px — I shrink on small screens but never exceed 400px.</div>max-width: 400px sets a ceiling, not a fixed size. On a wide screen the box stops growing at 400px (so the text stays a comfortable reading width). On a narrow phone it shrinks below 400px to fit. This is far more flexible than a plain width: 400px, which would overflow a small screen. The margin: 0 auto keeps it centred.
The padding problem
By default, width sets only the content width. Padding and border are added on top, so a 200px box with 20px padding is actually 240px wide. This breaks layouts.
The one-line fix
box-sizing: border-box makes width include padding and border — so 200px means 200px, full stop. Pros apply it to everything.
<style>
.a { width: 200px; padding: 20px; background:#fca5a5; } /* really 240px wide */
.b { width: 200px; padding: 20px; background:#86efac; box-sizing: border-box; } /* exactly 200px */
div { margin-bottom: 8px; }
</style>
<div class="a">Without border-box (actually 240px)</div>
<div class="b">With border-box (exactly 200px)</div>Both boxes say width: 200px and padding: 20px, yet the red one is wider than the green one. Why? The red box (.a) uses the default, where the 20px padding on each side is added on top of 200px, making it 200 + 20 + 20 = 240px. The green box (.b) adds box-sizing: border-box, which tells the browser to include the padding inside the 200px — so it stays exactly 200px and the content area simply gets smaller. That predictability is why pros turn it on everywhere.
Tip: A near-universal best practice is to put this at the top of every stylesheet: * { box-sizing: border-box; }. It saves countless layout headaches.
Q. What does box-sizing: border-box do?
✍️ Practice
- Create two boxes with the same
widthandpadding, one withborder-boxand one without; measure the difference. - Add
* { box-sizing: border-box; }to a stylesheet and see your layout behave.
🏠 Homework
- Add the global
box-sizing: border-boxrule to all your projects from now on.