Skip to content

CSS3 Box Sizing

The box-sizing property defines how the total width and height of an element are calculated, including its content, padding, and border.

The box-sizing property is widely supported by all modern browsers. Vendor prefixes are generally not needed anymore.

PropertyInternet ExplorerChromeFirefoxSafariOpera
box-sizingIE 8+ChromeFirefoxSafariOpera

By default, browsers use content-box. This means the width and height properties you set apply only to the element’s content area. Padding and border are added on top of that width and height.

Calculation: actual width = width + padding-left + padding-right + border-left + border-right actual height = height + padding-top + padding-bottom + border-top + border-bottom

This often leads to elements appearing larger than intended, especially when padding or borders are added.

Consider two divs, both set to width: 300px and height: 100px. Div 2 also has padding: 50px.

Div 1 (width: 300px, height: 100px, no padding): [Appears 300px wide]
Div 2 (width: 300px, height: 100px, padding: 50px): [Appears 400px wide (300 + 50 + 50)]

CSS for the above example (content-box is default):

.div1 {
width: 300px;
height: 100px;
border: 1px solid blue;
/* box-sizing: content-box; (default) */
}
.div2 {
width: 300px;
height: 100px;
padding: 50px;
border: 1px solid red;
/* box-sizing: content-box; (default) */
}

Historically, developers had to manually subtract padding and border widths from the desired total width, which was error-prone.

Modern Best Practice: box-sizing: border-box

Section titled “Modern Best Practice: box-sizing: border-box”

The border-box value makes layout much more intuitive. When you set box-sizing: border-box; on an element, the width and height properties define the total dimensions including content, padding, and border.

Calculation: width = content + padding + border height = content + padding + border

Now, if we apply border-box to both divs from the previous example:

Div 1 (width: 300px, height: 100px, border-box): [Appears 300px wide]
Div 2 (width: 300px, height: 100px, padding: 50px, border-box): [Also appears 300px wide! The content area shrinks to accommodate padding.]

CSS with border-box:

.div1-bb {
width: 300px;
height: 100px;
border: 1px solid blue;
box-sizing: border-box;
}
.div2-bb {
width: 300px;
height: 100px;
padding: 50px;
border: 1px solid red;
box-sizing: border-box;
}

Because border-box is significantly easier to work with, it’s a common best practice to apply it to all elements on a page using a universal selector.

Recommended global setting:

html {
box-sizing: border-box;
}
*, *::before, *::after {
box-sizing: inherit; /* Makes all elements inherit from html */
}

This setup ensures consistent and predictable sizing for all elements, including form elements which sometimes have inconsistent default box-sizing across browsers.