CSS3 Box Sizing
CSS3 box-sizing The property can make the width and height properties include padding and border.
Browser support
The numbers in the table indicate the version number of the first browser that supports this property.
The -webkit- or -moz- following a number is the prefix for the specified browser.
| property | |||||
|---|---|---|---|---|---|
| box-sizing | 10.0 | ||||
| 4.0 -webkit- | 8.0 | 29.0 | |||
| 2.0 -moz- | 5.1 | ||||
| 3.1 -webkit- | 9.5 |
Without the CSS3 box-sizing Property
By default, the width and height of an element are calculated as follows:
width + padding + border = the actual width of the element
**height + padding + border = the actual height of the element**
This means that when we set the width/height of an element, the actual displayed height and width will be larger (because the element's border and padding are also counted in the width/height).
This is a smaller box (width 300px, height 100px).
This is a larger box (width 300px, height 100px).
The two above
Example
.div1
{
width:
300px;
height:
100px;
border:
1px solid blue;
}
.div2
{
width:
300px;
height:
100px;
padding:
50px;
border:
1px solid red;
}
Try it »
Using this approach, if you want to obtain the smaller box including padding, you have to take the width of the border and padding into account.
CSS3's box-sizing property solves this problem nicely.
Using the CSS3 box-sizing Property
CSS3 box-sizing The property includes padding and border in the width and height of an element.
If you set on an element box-sizing: border-box; then the padding and border are also included in the width and height:
The two divs are now the same size!
Runoob Tutorial!
The following are two
box-sizing: border-box; simple examples of the property.
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;
}
Try it »
From the results box-sizing: border-box; the effect is better, and it is exactly what many developers need.
The following code lets all elements display their size in a more intuitive way. Many browsers already support box-sizing: border-box; (but not all - which is why input and text elements end up with different widths after setting width: 100%;).
It is recommended to use box-sizing for all elements:
Example
{
box-sizing:
border-box;
}
Try it »