box-sizing

Avatar of Sara Cope
Sara Cope on (Updated on )

UGURUS offers elite coaching and mentorship for agency owners looking to grow. Start with the free Agency Accelerator today.

The box-sizing property in CSS controls how the box model is handled for the element it applies to.

.module {
  box-sizing: border-box;    
}

One of the more common ways to use it is to apply it to all elements on the page, pseudo elements included:

*, *::before, *::after {
  box-sizing: border-box;
}

This is often called “universal box-sizing”, and it’s a good way to work! The (literal) width you set is the width you get, without having to perform mental math and manage the complexity that comes from widths that come from multiple properties. We even have a box-sizing awareness day around here.

Values

  • content-box: the default. Width and height values apply to the element’s content only. The padding and border are added to the outside of the box.
  • padding-box: Width and height values apply to the element’s content and its padding. The border is added to the outside of the box. Currently, only Firefox supports the padding-box value.
  • border-box: Width and height values apply to the content, padding, and border.
  • inherit: inherits the box sizing of the parent element.

Example

This example image compares the default content-box (top) to border-box (bottom):

The red line between the images represents the elements’ width value. Notice that the element with the default box-sizing: content-box; exceeds the declared width when the padding and border are added to the outside of the content box, while the element with box-sizing: border-box; applied fits completely within the declared width.

Using Box Sizing

Let’s say you set an element to width: 100px; padding: 20px; border: 5px solid black;. By default, the resulting box is 150px wide. That’s because the default box sizing model is content-box, which applies an element’s declared width to its content only, placing the padding and border outside the element’s box. This effectively increases how much space the element takes up.

If you change the box-sizing to padding-box, the padding is pushed inside the element’s box. Then, the box would be 110px wide, with 20px of padding on the inside and 10px of border on the outside. If you want to put the padding and the border inside the box, you can use border-box. The box would then be 100px wide — the 10px of border and 20px of padding are both pushed inside the element’s box.

Demo

More information

Browser support

ChromeSafariFirefoxOperaIEAndroidiOS
Any *†3 *†1 ‡7 *8 *2.1 *†Any *

* padding-box not supported

† older versions require -webkit prefix (Chrome 1-9, Safari 3-5, Android 2.1-3.x)

-moz prefix required up to version 28, unprefixed as of 29.