Skip to content
FORGENO ADS GAMESUnlock all $8

CSS · Unit 2: The box model · Lesson 2 of 5

box-sizing: border-box

By default, width sets only the content.

Opens this lesson in Code Academy. Lessons open one after another, and each unit opens when you pass the checkpoint quiz before it (you can take a checkpoint early to skip ahead). If this lesson is not open yet, the button shows you its unit on your map.

The idea

By default, width sets only the content. Padding and border are added on top, so a 200px box with 20px of padding on each side ends up 240px wide.

box-sizing: border-box makes width include the padding and border. A 200px box stays 200px, which is much easier to plan.

Most sites set it for every element at the top of their CSS: *, *::before, *::after { box-sizing: border-box; }

Worked example

CSS

div {
  width: 200px;
  padding: 20px;
  border: 4px solid steelblue;
  margin-bottom: 8px;
}

.b {
  box-sizing: border-box;
}

The HTML it styles

<div class="a">content-box</div>
<div class="b">border-box</div>

Box a is 248px wide (200 + 20 + 20 + 4 + 4). Box b is exactly 200px.

Key terms

box-sizing
border-box makes width include padding and border, which is easier to plan.

Practise it in Code Academy

It has 4 exercises (predict the output, multiple choice, fill in the blank and write code from a prompt) and takes about 6 minutes. Every answer is checked as you go, and feedback names the exact mistake. Hints and the solution are there if you get stuck.

Every lesson is free: no ads, no lives and no paywall.