CSS Box Sizing

Content Box

The default setting for the box model has the width and height property to set the width and height of the content area of the box.

The width of HTML elements is then calculated by the combined values of the width, padding, and border properties. Similarly the height of the HTML elements is calculated by the combined value of height, padding, and border properties.

With this default setting, we've set a width and height of 100px on the box. There's a 5px wide border and 10px for the padding. When we click on the buttons we'll see the total calculated value is 130px.

Breaking down the measurements it looks like this:

  • Total Width = width + padding-left + padding-right + border-left + border-right
  • Total Width = 100px + 10px + 10px + 5px + 5px = 130px
  • Total Height = height + padding-top + padding-bottom + border-top + border-bottom
  • Total Height = 100px + 10px + 10px + 5px + 5px = 130px

These values give us a width and height of 130px each.

Border Box

The default of content-box needs us to consider the width, height, border and padding property values separately while creating a layout.

Box sizing allows us to simplify the calculation of the total width and total height by using the width property value for overall width of the element including the border and padding and height property value for overall height of the element including the border and padding.

Because of great browser support, we are safe to rely on leveraging the css property box-sizing to change the box-sizing model to calculate everything from the root width and height. box-sizing:border-box;

When we click the buttons to display the total calculated width now - the box stays at 100px and the border and padding are calculated inside the width.

Paul Irish, a developer at google recommends assigning the box-sizing: border-box style to all of our HTML elementsopen in new window.

As we progress further along with our layouts we'll see the benefits of having these extra calculations done for us. It's a great advantage to have the total calculated width set by the width style.

Setting the box-sing for all elements

Before we start our CSS styles we can add the following code to set the box-sizing for every element on the page

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