Before discussing about the
box-sizing property, I think it is better to revise the CSS box model to clearly understand the way browsers calculate an element layout.
What is the box model?
The box model is the way in which the dimensions of an element are calculated. In the W3C specification the rendered width and height are calculated respectively as
width + padding + border and
height + padding + border.
So, when you define the
width of an element, this dimension represents the width of the content box, excluding the padding and the border.
However, there is another type of box model. In Internet Explorer 6, with “Quirks Mode” enabled, the
width of an element is calculated as the width between the borders of the box, including the padding and the border.
Switching between box models
box-sizing propriety accepts two values:
content-box is the behavior as specified by CSS2.1. The specified width and height apply to the
height respectively of the content box of the element. The padding and the border of the element are laid out and drawn outside the specified
height will include also any padding or border specified on the element. The content width and height are calculated by subtracting the border and padding widths of the respective sides.
Where can I use it?
border-box model can be handy if the element dimensions are expressed in percents. Therefore, you can build a responsive grid with
width in % units and
border in px units without adding an extra element inside.
Moreover, this propriety is really useful if the element cannot have a child as for instance
textarea elements. Indeed, by setting the
box-sizing propriety to
border-box and the
width to 100%, the element will always fill its parent, regardless
Nowadays, the browser support is quite wide.
This propriety works on:
- Firefox 1+ (with the -moz prefix)
- Safari 3+ (with the -webkit prefix)
- Opera 8.5+
- Internet Explorer 8+
I have written a simple method that extends the
box-sizing support also to IE6 and IE7.
Basically, this method scans all document’s elements and if the
box-sizing propriety is set to
height of that element are calculated (by subtracting padding and border to the rendered dimensions) and written inline.