CodeOath
← All posts
HTML & CSS70 min total · 18 parts

CSS Fundamentals: The Box Model, Specificity, Positioning, and Layout

Contents — Part 3 of 18: box-sizing: content-box vs. border-box
Part 3 of 18 · ~1 min

box-sizing: content-box vs. border-box

box-sizing decides what width/height actually measure.

.content-box-example {
  box-sizing: content-box; /* the CSS default */
  width: 200px;
  padding: 20px;
  border: 5px solid black;
  /* rendered width = 200 (content) + 40 (padding, both sides) + 10 (border, both sides) = 260px */
}

.border-box-example {
  box-sizing: border-box;
  width: 200px;
  padding: 20px;
  border: 5px solid black;
  /* rendered width = 200px, full stop — padding/border eat into the content area instead */
}

content-box is the CSS default for historical reasons, but it means width only describes the content area — padding and border are added on top of it, so the box grows every time you add padding. This constantly surprises people building a fixed-width layout: adding padding: 20px to a width: 200px box you expected to stay 200px wide instead makes it 240px wide (or 260px with the border above).

border-box is what almost every modern CSS reset applies globally, because it makes width/height describe the box's actual rendered size, padding and border included — matching what most people intuitively expect:

*, *::before, *::after {
  box-sizing: border-box;
}

With this reset in place, width: 200px always means 200px on screen no matter how much padding or border you add later, which is why it's close to universal in real projects.