Alex Meub

Use the Natural CSS Box Model

The CSS Box Model is used to describe how items are rendered (in boxes) from elements in the document tree. It determines how the content area, padding, border and margin of an element will be displayed. There are two types.

The W3C Box Model

CSS:
width: 300px;
height: 200px;
padding: 20px;
border: 5px solid #f00;
Actual Size
x

The W3C specification calls for the width property of any particular element to apply to the content area of that element. Because the width/height properties are applied to the content-area of the element, the total size of the element must be increased to account for the padding and border.

Total Width = left border width + left padding + width + right padding + right border width

This is annoying. If I specify a width of an element in CSS, the element should be that size not this weird calculation.

The IE Box Model

CSS:
width: 300px;
height: 200px;
padding: 20px;
border: 5px solid #f00;
Actual Size
x

Instead of implementing the box model according to the W3C specification, IE5 devs decided to implement it a different way. If a width is specified, IE’s box model includes padding and border into the width calculation and shrinks the content area of the element to account for padding/border.

Total Width = width

It is often referred to as the “Natural” or “Traditional” model because, unlike the W3C’s box model, it actually makes sense. When I specify a width, I’m saying “the width of this element should be x” not “the width of this element’s content area should be x”. I really don’t care if padding or border shrinks the size of my content area. The important thing is that when I specify the width of an element, it actually ends up being displayed that size on the page.

Using a Natural Box Model

The following CSS reset by Paul Irish applies this natural box model to all elements:

*, *:before, *:after {
  -moz-box-sizing: border-box; 
  -webkit-box-sizing: border-box; 
  box-sizing: border-box;
 }

It is supported in IE8+, FF2+ and pretty much every browser version of the last decade. Do yourself a favor and use it.