Understanding CSS3 box-sizing
There has long been a debate about how the box model should work. The developers of IE5 chose to exercise their creative license and use a model that differed to the official W3C specification of the time. Many believed that the IE model made more sense and in this article we’re going to explore the differences and see what we can do about it in CSS3.
Know your box model? Skip ahead, sparky!
Something About Boxes..?
I find it often helps to think of the box model along the same lines as wrapping up a mug as a gift.
- You start with the mug (or the content, in our case).
- You then add some packing peanuts (this is our padding).
- After that, you put all of that in a cardboard box (our border).
- Finally, you wrap it all up in some nice wrapping paper (our margin).
As is commonplace, we’ll demonstrate this with a hideously Photoshopped mash-up of pictures:

So, What’s the Problem?
The problem is the differences between the two box models that were eventually implemented. The official specification states that the width and height should be calculated by the actual size of the box content. Microsoft decided in IE5 that the width of the element should be determined by the content, padding and borders and that created some discrepancies.

As you can see, the difference in width calculations could cause havoc and break layouts.
box-sizing
Now, with CSS3, we have a choice of which box model to use. The box-sizing property allows you to select your flavour.
box-sizing: content-box;
-moz-box-sizing: content-box;
-webkit-box-sizing: content-box;
The code above will give you the specification based width and height calculations.
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
The border-box value will give you the IE5 calculation method.
When Will I Ever Use This?
I actually think the IE5 method makes a lot of sense in some situations and becomes really useful when we’re trying to increase the readability and reusability of our CSS.
div {
box-sizing: border-box;
width: 200px;
border: 5px solid #000;
padding: 2px;
}
The div in this example will be 200 pixels wide no matter how you adjust the values of the border and padding properties.
div { box-sizing: content-box; /* This is the default layout but I’ve included it here for readability */ width: 200px; border: 5px solid #000; padding: 2px; }
This div will be 214 pixels wide (200 (width) + 10 (border) + 4 (padding)).
I would primarily use the border-box (IE5 method) box model for layout as it creates rock solid dimensions for your elements. Using it for anything other than that may end up getting complex and confusing.
I’ve set up a little demonstration page. It’s worth bearing in mind that box-sizing will also work with min and max height and width.
If you’re really interested in box-sizing, James Hopkins has a great write-up on the ins and outs.
What are your views on box-sizing and the box model?