box-sizing

Back to the index.

This page tests box-sizing, but first explains why we need it.

Box models

  1. In the W3C box model, the width of an element gives the width of the content of the box, excluding padding and border.
  2. In the traditional box model, the width of an element gives the width between the borders of the box, including padding and border.

By default, all browsers use the W3C box model, with the exception of IE in "Quirks Mode" (IE5.5 Mode), which uses the traditional one.

Example

The image below summarizes the difference. Both element have these styles:

width: 250px;
height: 100px;
border: 5px solid #6374AB;
padding: 10px;

The first uses the traditional box model, while the second uses the W3C one.

The two box models

The best?

Personally I find W3C's box model counter-intuitive. To quote myself:

Logically, a box is measured from border to border. Take a physical box, any box. Put something in it that is distinctly smaller than the box. Ask anyone to measure the width of the box. He'll measure the distance between the sides of the box (the 'borders'). No one will think of measuring the content of the box.

Web designers who create boxes for holding content care about the *visible* width of the box, about the distance from border to border. The borders, and not the content, are the visual cues for the user of the site. Nobody is interested in the width of the content.

box-sizing

box-sizing allows you to switch box models.

box-sizing: border-box
box-sizing: content-box

The first declaration will cause the box sizes to be applied to the border and everything inside it (traditional model), the second one will cause the box sizes to be applied to the content only (W3C model).

Mozilla supports an additional padding-box value, which will cause the sizes to be applied to the padding and content, but not the border.

Some boxes for your testing pleasure. The styles of the boxes are:

div.test {
	width: 300px;
	padding: 10px;
	border: 5px solid #000000;
	margin-left: 10%;
	margin-bottom: 10px;
	margin-top: 10px;
}

The indicated box-sizing declaration is added inline:

box-sizing: content-box
box-sizing: border-box
box-sizing: padding-box
Traditional box model width
W3C box model width
Mozilla's padding-box
-moz-box-sizing: content-box
-moz-box-sizing: border-box
-moz-box-sizing: padding-box
Traditional box model width
W3C box model width
Mozilla's padding-box
-ms-box-sizing: content-box
-ms-box-sizing: border-box
-ms-box-sizing: padding-box
Traditional box model width
W3C box model width
Mozilla's padding-box
-webkit-box-sizing: content-box
-webkit-box-sizing: border-box
-webkit-box-sizing: padding-box