CSS - Box Sizing
Overview
Quick links: Exercises • Checks • Print as PDF
Estimated time: 8–10 minutes
Box sizing controls whether width/height includes padding and borders. Understanding this prevents sizing surprises.
Learning Objectives
- Explain the difference between
content-box
andborder-box
. - Apply the universal border-box reset responsibly.
Details & Examples
box-sizing: border-box;
makes width/height include padding and border—generally easier to reason about.
/* Universal reset - commonly used */
*, *::before, *::after {
box-sizing: border-box;
}
.box-content {
box-sizing: content-box; /* default */
width: 200px;
padding: 20px;
/* Total width: 240px (200 + 20 + 20) */
}
.box-border {
box-sizing: border-box;
width: 200px;
padding: 20px;
/* Total width: 200px (padding included) */
}
Common Pitfalls
- Mixing box-sizing models in the same layout can cause confusion.
- Third-party components might assume
content-box
.
Checks for Understanding
- What is the total width of an element with
width: 100px; padding: 10px; border: 2px solid;
usingcontent-box
? - What about with
border-box
?
Show answers
- 124px (100 + 10 + 10 + 2 + 2)
- 100px (padding and border are included in the width)
Exercises
- Create two boxes, one with
content-box
and one withborder-box
, both set towidth: 200px; padding: 20px;
. Verify the visual width difference. - Add a universal border-box reset and explain how it simplifies layout calculations.
Suggested answers
- The content-box total width is 240px; border-box remains 200px since padding is included.
*,*::before,*::after{ box-sizing:border-box }
makes element width include padding/border, easing responsive sizing.