Fit any screen width

INPUT · Slides

Count the space inside the width

01 / 05

You set it to 100% and it still spills out

You set a width of 100%, added some space, and the box went outside — that is not a typo.

Once you know what CSS means by width, the reason falls neatly into place.

.card {  width: 100%;  padding: 16px;}

02 / 05

width meant "the width of the contents"

Ordinarily width is the width of the contents only. The space (padding) and the border (border) get added outside it.

So the size you see comes to:

  • contents 100%
  • plus 32px of space at the sides
  • plus the borders at the sides

Which is always bigger than the box outside.

03 / 05

Change how the sum is done

Write box-sizing: border-box; and the meaning of width changes to "the size including the space and the border".

The space is no longer added outside; the contents shrink to make room. So 100% fits exactly.

.card {  width: 100%;  padding: 16px;  box-sizing: border-box;}

04 / 05

Set it for everything at once

This is not something you vary box by box. Mix two ways of counting on one page and you will struggle to find the cause of any breakage.

List selectors with commas and you can set them all together. Writing it at the top of your CSS is a good habit.

.inner, .card, .panel {  box-sizing: border-box;}

05 / 05

Fix the root of the breakage

Widths as percentages, restacking when narrow, and now counting the same way everywhere. Those three see off most breakage.

Have a go.