CSS: changing the box-sizing property

What is it?

The standard CSS box model works in the following manner (ignoring early versions of Internet Explorer). Total width of the box = declared width + padding + border (please refer to the diagram below).

Standard box model

So in our CSS code for example, we would have something like this:

div.our-box {
    width: 100px;
    padding: 20px;
    border: 2px solid red;
}

So our div box instead of having a width of 100px as declared, would actually end up with a rendered width of 144px (100px + 20px padding + 20px padding + 2px border + 2px border).

Wouldn’t it be easier if the box was rendered at 100px as we specified regardless of the border and padding? This is where the new “box-sizing” property in CSS3 comes in.

Why change it?

If we set the box-sizing property to border-box (instead of the default value of content-box), this then renders the box with the width and height that we have declared, and any border and padding are subtracted or cut inside the box. This can make life a lot easier when most times we know what size we want our box to be and we can change padding and border values without affecting the box width. This also comes in very handy when you want to set your box width to 100% and then all padding and borders are subtracted from this instead of added as per the default option.

Box-sizing available values

As mentioned previously, the box-sizing CSS3 property has a default value of content-box but has a total of 3 different options. The 3 options are as follows:

  • content-box – This is the default value. The padding and border of the element are drawn outside the specified width and height.
  • border-box – The padding and border of the element are drawn inside the specified width and height.
  • inherit – The value of the box-sizing property should be inherited from the parent element

How to change it?

By declaring the following CSS code, this will apply the more logical box model to all your HTML elements and should make life easier, especially when working with layouts.

/* Use a more sensible box layout model for all elements */
* {
  -moz-box-sizing: border-box; /* Firefox */
  -webkit-box-sizing: border-box; /* Old versions of iOS & Android */
  box-sizing: border-box; /* Everyone else... */
 }

So given the same example used previously…

div.our-box {
    width: 100px;
    padding: 20px;
    border: 2px solid red;
}

… we will now end up with a rendered div box of 100px exactly as we have declared it. And to calculate the maths we would end up with a content area with a width of 100px – 20px padding – 20px padding – 2px border – 2px border = 56px.

Comments