Typically, the visible width or height of an element's box on a web page depends on its width
, height
, padding
, and border
properties. For instance, applying padding
and border
to a <div>
element with 100% width
may trigger a horizontal scrollbar, as shown below.
.box {
width: 100%;
padding: 20px;
border: 5px solid #f08080;
}
This has long been a common issue faced by web designers. However, CSS3 introduces the box-sizing
property to address this challenge, simplifying CSS layouts. With box-sizing
, any specified padding
or border
on the element is included inside the content area. Consequently, the rendered width and height of the element match the specified CSS width
and height
properties.
.box {
width: 100%;
padding: 20px;
border: 5px solid #f08080;
box-sizing: border-box;
}
Observing the output of this example, you'll notice the scrollbar has vanished.
Note: When using the CSS box-sizing
property, the resulting width and height of the content area are calculated by subtracting the border
and padding
widths from the specified width
and height
properties.
The CSS box-sizing
property simplifies the creation of multiple column layouts using percentages. You no longer need to fret over the final size of element boxes when adding padding or borders to them.
The following example illustrates a two-column layout where each column possesses equal width and is arranged side-by-side using the float
property.
.box {
width: 50%;
padding: 20px;
background: #f2f2f2;
float: left;
box-sizing: border-box;
}
Similarly, you design more complex layouts using this simple technique.
.box {
width: 30%;
padding: 20px;
margin-left: 5%;
background: #f2f2f2;
float: left;
box-sizing: border-box;
}
.box:first-child {
margin-left: 0;
}