HTML & CSS82 min total · 18 parts
CSS Fundamentals: The Box Model, Specificity, Positioning, and Layout
Part 3 of 18 · ~2 min
box-sizing: content-box vs. border-box
box-sizing is the property that settles what width and height actually measure.
.card {
box-sizing: content-box; /* the CSS default, and the one nobody would pick on purpose */
width: 260px;
padding: 16px;
border: 1px solid #ddd;
/* rendered width = 260 (content) + 32 (padding, both sides) + 2 (border, both sides) = 294px */
}
Under content-box, width is only ever a promise about the content box — padding and border don't subtract from that number, they pile on beside it, so the rendered size creeps upward every time either one grows. That's exactly the trap sitting in the card from the intro: a grid column built to hold exactly 260px, and a card that actually measures 294px once its padding and border are tallied up. The card doesn't just look a little tight — it overflows the column outright, and the third card in every row gets shoved onto a new line nobody designed for.
.card {
box-sizing: border-box;
width: 260px;
padding: 16px;
border: 1px solid #ddd;
/* rendered width stays 260px — padding and border carve into the content area instead of adding to it */
}
border-box changes what width is a promise about: instead of describing the content alone, it describes the finished box, border and padding already absorbed into that number. Add more padding later — a bigger touch target for the button, say — and the content area shrinks slightly to make room, but the outer edge of the card never moves. That's the behavior most people already assume width has, which is exactly why this gets switched on once, near the top of the stylesheet, and then never thought about again:
*, *::before, *::after {
box-sizing: border-box;
}
With that reset in place, the category grid's math works again: every card is exactly as wide as its column, no matter how its padding or border changes later. This one rule is doing so much quiet work that the rest of this reference simply assumes it's there.