CSS3 Box Sizing
CSS3 box-sizingThe property can set the width and height properties to include padding and border.
Browser Support
The numbers in the table indicate the version number of the first browser that supports the property.
The -webkit- or -moz- immediately following the numbers 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 using the CSS3 box-sizing property
By default, the width and height of an element are calculated as follows:
width + padding + border = actual width of the element
height (height) + padding (padding) + border (border) = 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 included in the width/height calculation).
Although the above two <div> elements have the same width and height settings, their actual displayed sizes are inconsistent because div2 has a specified padding:
Example
width: 300px;
height: 100px;
border: 1px solid blue;
}
.div2 {
width: 300px;
height: 100px;
padding: 50px;
border: 1px solid red;
}
Try it Yourself »
With this approach, if you want to get the smaller box and include the padding, you have to take the width of the border and padding into account.
CSS3'sbox-sizingThis property solves this problem well.
Using the CSS3 box-sizing property
CSS3 box-sizingThe property includes padding and border in an element's width and height.
If set on the elementbox-sizing: border-box;Then padding and border are also included in the width and height:
The following are two <div> elements with the addition ofbox-sizing: border-box;A simple example of the property.
Example
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 Yourself »
From the results,box-sizing: border-box;The effect is better, and it is exactly what many developers need.
The following code allows all elements to display their sizes in a more intuitive way. Many browsers already support itbox-sizing: border-box;(but not all - this is why input and text elements have different widths after being set to width: 100%;).
It is recommended that all elements use box-sizing:
other extensions