CSS: Box Sizing

By Xah Lee. Date: . Last updated: .

CSS box-sizing

box-sizing property controls the meaning of width property.

box-sizing: content-box
Default. Width means the content width. Padding and border grows outside of it.
box-sizing: border-box
Meaning of width means from border to border.

The default behavior is called CSS Box Model.

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.

Examples

Following is 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;

Following is 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;

Following is 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

/* make all width border based */
html {
  box-sizing: border-box;
}
*, *:before, *:after {
  box-sizing: inherit;
}

CSS, border, margin, box model