VCF

Unit 3 · CSS: the look and the layout

Why a 200px box ends up wider than 200px

By default, width sets only the content area. Padding and border are added on both sides, so width: 200px with 12px padding and a 4px border is 232px wide. box-sizing: border-box makes the width include them.

The mix-up

What people often think

“If width is 200px, the box is 200px wide.”

What the tutor says

By default, width is only the content. Padding and border are added on both sides: 200 + 12 + 12 + 4 + 4 = 232px.

How many times does the padding count: once, or once for each side?

How it works

Count both sides: 200 + 12 + 12 + 4 + 4 = 232. That extra 32px is why a box spills out of a column that should fit it.

Shrinking the width by hand, deleting the padding or adding overflow: hidden all hide the problem: the first breaks as soon as the padding changes, the second cramps the text, and the third just cuts off the edge. Change how the width is counted instead.

Side by side

The mix-upCSS
.banner {
  width: 360px;
  padding: 20px;
  border: 4px solid;
}  /* actually 408px wide */
Padding and border sit outside the 360px.
What worksCSS
.banner {
  box-sizing: border-box;
  width: 360px;
  padding: 20px;
  border: 4px solid;
}  /* 360px, padding included */
The width now includes padding and border.

Close cousins of this mix-up

The tutor watches for these in the same lesson.

  • “To fit the padding in, I have to make the width smaller.”

    Leave width at 240px. By default, width is only the content, and padding and border are added around it: 240 + 40 + 10 = 290.

  • “The padding is the problem, so remove it.”

    The padding is what gives the text room to breathe. Leave it in, and add box-sizing: border-box so the 360px includes it.

  • “Hiding the overflow fixes it.”

    overflow: hidden only cuts off the part that sticks out, so the right border disappears. The banner is still 408px wide. Change how its width is counted instead.

Practise it with a tutor watching

The box model

Predict exactly how much space a box takes, and size it with padding, border and margin.

20 minutes See it Build it Break it Say it
Start the lesson

Free, no account needed.