🎓 A1Learner
🔍

CSS Box Sizing

Box sizing is the rule that decides what the width property covers. The box-sizing property sets that rule for an element.

The default adds up

The content-box value is the default. Padding adds to the stated width, so the box ends up 240 pixels wide.

.box {
  box-sizing: content-box;
  width: 200px;
  padding: 20px;
}

Border-box keeps the width

The same numbers now give a different total. The padding fits inside the stated width of 200 pixels.

.box {
  box-sizing: border-box;
  width: 200px;
  padding: 20px;
}

Set it on every element

The universal selector applies the rule to the whole page. The border now fits inside the stated width too.

* {
  box-sizing: border-box;
}
.box {
  width: 200px;
  padding: 20px;
  border: 5px solid blue;
}

Example

* {
  box-sizing: border-box;
}
.box {
  width: 240px;
  background-color: lightblue;
  padding: 20px;
  border: 4px solid blue;
}
button {
  padding: 8px 16px;
}

Key points

  • content-box: the default value, where width covers the content only
  • border-box: the value where width covers the content, padding and border
  • With border-box, the stated width is the full width of the box.
  • Margins stay outside the width under both values.
  • Many projects set border-box on every element with the universal selector.

In this example, the universal selector sets border-box on every element. The box states a width of 240 pixels. Its padding and its border fit inside that width, so the box stays 240 pixels wide. The button follows the same rule through the universal selector.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

A box uses border-box with width 200px, padding 20px and a 5px border. How wide is the box in total?