Skip to main content

CSS Box Sizing

An element's width and height can be worked out in two ways, with padding and borders counted or left out, and the CSS box-sizing property picks which one applies.

Left alone, the browser leaves them out of the number you set and adds them afterwards:

  • actual width = width + padding + border
  • actual height = height + padding + border

So the padding and border sit on top of whatever size you specified, and an element often renders larger than you expected. box-sizing is the fix for this.

Example

Both <div> elements ask for the same width and height, yet they render at different sizes: only the second has the extra padding that grows it.

Prompt
Create two div elements, both with width: 300px and height: 100px. The first div has a 1px solid blue border and no padding. The second div has a 1px solid red border and 50px padding. Show how they end up different sizes because padding is added to the specified width/height.
Output: complete HTML page

The CSS box-sizing Solution

With box-sizing, padding and border can become part of the total width and height you declare. The value that does this is box-sizing: border-box;, which keeps them inside the calculation.

The outcome is so much better that many developers would like it on every element of their pages. Browsers already apply box-sizing: border-box; to many form elements, though not to all of them, which explains why inputs and text areas can differ at width: 100%;.

Setting box-sizing: border-box; on everything is both safe and sensible.

Example

Add box-sizing: border-box; to those two <div> elements and they now render at an identical size.

Prompt
Create two div elements, both with width: 300px, height: 100px, and box-sizing: border-box. The first div has a 1px solid blue border. The second div has 50px padding and a 1px solid red border. Both divs should appear the same size because box-sizing: border-box includes padding and border in the width/height.
Output: complete HTML page

Universal box-sizing

To cover the whole page, put box-sizing: border-box; on the universal selector *.

Prompt
Use the universal selector (*) to apply box-sizing: border-box to all elements on the page. Add two div elements with width: 300px, height: 100px, different padding and borders, to demonstrate they remain the same total size.
Output: complete HTML page