Lesson 10 +10 XP

Box Sizing

box-sizing

box-sizing decides WHETHER the width/height you set includes padding and border.

The problem

By default (content-box), the width you set only counts the CONTENT. Padding and border are ADDED on top. The box becomes bigger than you asked for!

div {
  width: 300px;
  padding: 30px;
  border: 5px solid;
  /* total width = 300 + 30 + 30 + 5 + 5 = 370px! */
}

The fix

box-sizing: border-box makes the width include padding and border. Box stays exactly 300px wide, and your content shrinks.

div {
  box-sizing: border-box;
  width: 300px;
  padding: 30px;
  border: 5px solid;   /* total stays 300px */
}

The modern default

Lots of sites apply it to everything:

* {
  box-sizing: border-box;
}

This makes sizing predictable for the whole site.

When to watch out

  • content-box = width counts content only (CSS default).
  • border-box = width counts content + padding + border.
  • With border-box, box widths add up predictably for grids.

TL;DR

  • default: content-box (width = content only).
  • border-box: width includes padding + border.
  • Apply to * for predictably sized sites.