CSS3 Box Sizing
The CSS3 box-sizing
property allows the width and height properties to include the padding and border.
Browser Support
The numbers in the table specify the first browser version that fully supports the property.
The -webkit- or -moz- following the number is the prefix for the specified browser.
Property | |||||
---|---|---|---|---|---|
box-sizing | 10.0 <br>4.0 -webkit- | 8.0 | 29.0 <br>2.0 -moz- | 5.1 <br>3.1 -webkit- | 9.5 |
Without Using CSS3 Box-Sizing Property
By default, the width and height of an element are calculated as follows:
width + padding + border = actual width of an element
height + padding + border = actual height of an element
This means that when you set the width/height of an element, the element often appears bigger than you set (because the element's border and padding are added to the element's specified width/height).
The two <div> elements below have the same width and height set, but the actual size differs because div2 has padding specified:
Example
.div1 { width: 300px; height:
100px; border: 1px solid blue; }
.div2 { width: 300px;
height: 100px; padding: 50px;
border: 1px solid red;}
Using this method, if you want to get a smaller box with padding, you have to consider the width of the border and padding.
The CSS3 box-sizing
property solves this problem.
Using CSS3 Box-Sizing Property
The CSS3 box-sizing
property includes the padding and border in an element's width and height.
If you set box-sizing: border-box;
on an element, the padding and border are included in the width and height:
Here are two <div> elements with the box-sizing: border-box;
property added.
Example
.div1 { width: 300px; height:
100px; border: 1px solid blue;
box-sizing: border-box;}
.div2 { width: 300px;
height: 100px; padding: 50px;
border: 1px solid red; box-sizing: border-box;}
The result is that box-sizing: border-box;
works better and is the effect many developers want.
The following code allows all elements to display their sizes in a more intuitive way. Many browsers already support box-sizing: border-box;
(but not all - which is why input and text elements have different widths when set to width: 100%;).
Using box-sizing for all elements is recommended:
Example
* { box-sizing: border-box;}