Improve Interface Development with Box Sizing

Whether you’re new to css layouts or a ninja css warrior we both share one common enemy: The Box Model.

The box-model is the way we calculate the width and height of an object. The W3C modal calculates the width and height by adding the padding and border to the width you specify ( width + padding + border / height + padding + border ). This is a pain because when we want to specify a width to be 400px wide, we first need to subtract the difference of the padding and border to make a 400px wide box. If we had a border of 10px and a padding of 20px, the width would be 340px wide (400 – 20 – 40 = 340px).

IE6 has a quirk where its box model calculated the width with the border and padding inside. When I started out as a developer I thought this was odd as other browsers calculated differently. This is how the border-box calculates the width. This really comes in handy when used for responsive design and fluid grids!

Box-sizing does take two values. First, the border-box as we have described above where the padding and border are inside. The second value, which is commonly used across browsers is content-box specified by CSS2. The padding and border are included to the width and height.

box-size comparison

Using box-sizing you can have fluid grids and keep all your gutters and borders inside. This makes it easier when starting out with responsive web design. We have begun using the border-box value for the box-size property in our recent Github pages (Omni Auth, Green Onion, Grape). Take a look at them as examples of how simple designs can be responsive with box-sizing: border-box property.

You can also play with sample code at Codepen.io.

Browser Support

  • Firefox 1-3, un-prefixed in current version
  • Safari 3, un-prefixed in current version
  • IE8+

code

  * {   -moz-box-sizing: border-box;   -webkit-box-sizing: border-box;   box-sizing: border-box;   }

By using the * you make all elements on the page use the box-sizing property.

If you have not started using box-sizing, I highly recomend using it in your projects. For the vetrans that know the old box modal this will help you with responsive web design. As mobile takes over, responsive design will become common practice, and the box-sizing property will become your new best friend!