Box Sizing: Border-Box
What is Box Sizing?
Imagine ordering a custom 200cm wide dining table. When it arrives, you discover the manufacturer added 10cm wide wooden borders on each side, making the table 220cm wide in total. It no longer fits through your dining room door! You expected the borders to be *included* within the 200cm width, not added on top of it.In CSS, browser engines calculate the total width of elements in two different ways depending on the box-sizing property:
content-box (Default): The width you specify only sets the size of the content. Any padding and borders are added *on top* of the width, expanding the box. (E.g., width: 200px + padding: 20px + border: 2px = total width of 244px!).border-box (Highly Recommended): The width you specify is the absolute size of the outer box. Any padding and borders are drawn *inside* that width, keeping the box size stable. (E.g., width: 200px total width. Content space shrinks to fit the padding and border!).Why does it matter?
Calculating widths withcontent-box makes responsive layouts a nightmare. If you set two columns to width: 50% so they sit side-by-side, but then add 10px of padding, the total width exceeds 100% and the columns break, collapsing onto separate lines. Switching to border-box makes layout math clean and predictable.
Syntax Breakdown
Apply box-sizing globally using the universal selector*:
* {
box-sizing: border-box;
}
Common Mistakes
border-box to a few classes, you will spend hours debugging why some columns fit and others collapse. Always place box-sizing: border-box; in a universal * rule at the very top of your stylesheet!Quick Reference
content-box โ Default browser behavior (width = content only; padding/borders add to total size).border-box โ Safe modern layout standard (width = absolute outer boundary; padding/borders fit inside).Your Task
Apply `box-sizing: border-box;` inside the universal `*` selector rule.
index.html
Type code above to start the lesson.
Live Preview