CSS border-box

The typical CSS "box model" (also known as content-box) will produce something like this:

width + padding + border = total/visible width of box
height + padding + border = total/visible height of box

Lets look at the example div below, with the typical box-sizing: content-box.

div {
 width: 240px;
 height: 240px;
 padding: 20px;
 border: 10px solid #fff;

In this case the padding and border will apply to the outside producing at total visible width of 300px (240px + 40px + 20px). We'd usually need to reduce the width of the box until everything fits just right.

Or we can add this little bit of magic and it will change that altogether!

* { 
 -webkit-box-sizing: border-box; /* safari, chrome */
 -moz-box-sizing: border-box; /* firefox */
 box-sizing: border-box; /* ie8+, opera */

With the box-sizing CSS3 property, the padding and border will now be inside the width of the box.

This is especially useful when you are floating divs and want to give them a width (33% for example) with padding and border. Now they will all be side-by-side, taking the entire width of the parent div.

Shane Graham

Shane Graham

Shane Graham is a senior Drupal developer and co-founder of Deck Fifty Design.

Get in touch

Let's go!

We look forward to hearing from you!