CSS3 box-sizing attribute

CSS3 is going to include a new attribute called box-sizing so we can choose whether the width set on an element will include borders and padding or whether borders and paddings will be added to the width.

The difference is basically the difference between the IE5 and W3C box models. The default will still be the W3C way we’re all used to where the padding and borders will be added to the width, it’ll just be possible to opt into the other way when it makes things easier.

How it works

Set the box-sizing style to content-box to get the traditional W3C box model. In this case the total width of the element will be the width set on the element plus the width of the borders and padding. If you had an element with a width of 30 pixels and a border of one pixel, the total width of the element would be 32 pixels:

  1. #div1{ box-sizing: content-box;}

It can also be set to border-box to have borders and paddings included in the width. If you had an element with a width of 30 pixels and a border of one pixel the total width of the element would still be 30 pixels:

  1. #div2{ box-sizing: border-box; }

Here’s how it would look in the browser. The top element has box-sizing set to content-box and the bottom has it set to border-box:

content-box fits inside the parent container while border-box overlaps
See code

Why’s this useful?

I’ve always found the way the browser works out dimensions (the CSS box model) by adding the borders to the width set on the box a little frustrating when working with percentage widths.

Imagine you’re creating a two column layout. The left column should be 30% and the right 70%:

  1. .left{
  2.     float: left;
  3.     width: 30%;
  4.     background-color: pink;
  5.     border: 3px red dotted;
  6.     height: 150px;
  7. }
  8. .right{
  9.     float: left;
  10.     background-color: lightgreen;
  11.     width: 70%;
  12.     border: 3px green dotted;
  13.     height: 150px;
  14. }
  1. <div class="left">content-box</div>
  2. <div class="right">box-sizing</div>

If you add a border to either box, the total with of the elements will be greater than 100% so the second box will be pushed onto the next line:

But if we switch the box-sizing mode to border-box, we can set a border and the box will still be exactly the width that we want:

When’s it coming?

When IE8 comes out this will be supported by all four of the big browsers.

Safari – supported with -webkit-box-sizing since Safari 3.

Opera – supported in the latest version of Opera (9.5)

Firefox – supported with the -moz-box-sizing since Firefox 1.1.

Internet Explorer – supported with -ms-box-sizing in the IE8 beta 1 and without the prefix in IE8 beta 2.

More information

Posted on 20 Oct 08 by Helen Emerson (last updated on 20 Mar 13).
Filed under CSS