CSS box-sizing Property

For this demonstration, recall the CSS Box Model.

The box-sizing property affects how the box model is calculated. The CSS default is content-box, which is explained in the CSS Box Model notes.

A diagram of the CSS Box Model

The two colored boxes below demonstrate the effect of setting the CSS box-sizing property to either content-box or border-box. Each box has the following CSS properties set:

.box {
   border: 5px solid rgba(50, 100, 255, .2);
   padding: 50px;
   margin: 20px;
   width: 600px;
}

Containing box set to 1000px. Each grid square = 100px.

Heading One

This section uses box-sizing: content-box

This box is 600px wide. With content-box, only the actual width of the content is used for the width argument. The content box is set to 600px wide. To calculate the total width, you must add the padding, border and margin together.

This is the default method.

Heading One

This section uses box-sizing: border-box

The width is calculated based on the visible area of the box. This includes the content, padding, and border.

This is new in CSS3 and is the preferred approach because generally more intuitive.

Definitions

content-width box model

    Total Width             Visible Width           Content Width

    left margin        |                      |
  + left border        |                      |
  + left padding       |     left border      |
  + width (in CSS)     |   + left padding     |
  + right padding      |   + width (in CSS)   |
  + right border       |   + right padding    |
  + right margin       |   + right border     |    width (in CSS)
 ------------------       ------------------     ------------------
  = total width            = visible width        = content width

border-width box model

    Total Width             Visible Width           Content Width

                      |                      |      width (in CSS)
                      |                      |    - left padding
  + left margin       |                      |    - left border
  + width (in CSS)    |                      |    - right border
  + right margin      |      width (in CSS)  |    - right padding
 ------------------       ------------------     ------------------
  = total width            = visible width        = content width

Using a box-sizing Reset

Since the border-box setting is so much more intuitive, it's common practice to simply reset the box-sizing property on all elements to border-box.

The box-sizing property must apply to all elements on a page, but also leave room to be overriden on a case-by-case basis. Here is the common snippet of code know as the box-model reset:

html {
   box-sizing: border-box;
}

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

This code should be placed at the top of your CSS, after the reset or normalize styles.

For more information on the box-sizing reset, see these articles:

For more information on the CSS Box Model, see: