CSS: Box Sizing

By Xah Lee. Date: . Last updated: .

box-sizing property controls the meaning of width property.

Normally, width means the content of a element. If you add padding and border, the result width from border to border will be bigger than the width value you used.

Suppose you have 2 div each has width: 50%. Now you add padding to it, suddenly, your boxes isn't side by side anymore, they don't fit. Each box's actual width from border to border is 50%+ padding + border.

But if you say box-sizing:border-box, your boxes are side by side again.

[see CSS: Margin vs Padding]

[see CSS: Border, Outline]

Propertie Values

The default behavior, is called “CSS Box Model”.

Examples

Here's a box with width 200px and padding and border. The actual width from border to border is 250px.

display: inline-block;
width:200px;
padding: 20px;
border: solid 5px blue;
box-sizing:content-box;

Here's a box with width 200px and padding, and using box-sizing:border-box;. The actual width from border to border is 200px.

display: inline-block;
width:200px;
padding: 20px;
border: solid 5px blue;
box-sizing:border-box;

Here's a box with width 200px and no padding, for comparison.

display: inline-block;
width:200px;
box-sizing:border-box;

Note: display: inline-block is used to force content stay inside the box.

Site Wide Border Model

It's a good idea to add this to your CSS, to make all width border based.

html {
  box-sizing: border-box;
}
*, *:before, *:after {
  box-sizing: inherit;
}

Box Model, Width, Padding, Margin, Border

  1. CSS: Margin vs Padding
  2. CSS: Border, Outline
  3. CSS: Box Sizing
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog