CSS Box Sizing
CSS Box Sizing
Compare content-box and border-box sizing to understand why two boxes with the same declared width may occupy different spaces.
What you’ll learn
- Compare content-box and border-box.
- Calculate visible width with padding and border.
- Choose box sizing appropriate for components.
Understand the concept
With box-sizing: content-box, width: 240px means the content box is 240px wide; padding and borders increase its rendered outer width. With box-sizing: border-box, the declared width includes content, padding and border, making layout math simpler.
Many projects apply box-sizing: border-box to all elements and their pseudo-elements through a global reset. This is a project convention, not a change to the browser’s default.
Visualize the relationship
Content-box default
A 240px content width grows after padding and border are added.
HTML
<div class="sized">content-box</div>CSS
.sized { box-sizing: content-box; width: 240px; max-width: 100%; padding: 20px; border: 5px solid #2563eb; background: #dbeafe; }Rendered output
Observe: On a wide enough screen, the outer box occupies 290px: 240 + 40 padding + 10 border.
Border-box model
The same declared width includes padding and borders.
HTML
<div class="sized">border-box</div>CSS
.sized { box-sizing: border-box; width: 240px; max-width: 100%; padding: 20px; border: 5px solid #0f766e; background: #ccfbf1; }Rendered output
Observe: The outer bordered box fits within 240px; the content area becomes correspondingly smaller.
Explain the result
Outer width with content-box = content width + left/right padding + left/right border; with border-box the declared width already includes padding and border.
Compare the two examples: identify the selector, each changed property, and which visible part of the output proves that the CSS took effect.
Common mistakes to avoid
- Changing box-sizing changes which part of the box width refers to.
- Margins are never included inside an element’s declared border-box width.
Try it yourself
Add a 10px border to both demos. Compute their outer width from the declarations and verify visually.
Before changing the code, predict what will change. Then verify by checking the rendered result.
Check your understanding
What you should remember
Use border-box for easier component sizing and remember margins still sit outside.
Revisit the rendered examples if the rule still feels abstract. Change one declaration at a time so you can connect cause and effect.
Reaching the recap and completing the quizzes are separate milestones.