CSS border-box everywhere

CSS Box-Sizing

I can only presume the folk who originally came up with the way CSS sizes its internal boxes were as mad as a box of frogs.

Take, for example, this bit of code:

.myblock {
   width: 200px;
   padding: 5px;
   border: 1px solid green;

If you said something was 200px wide and then added 5px of padding and a 1px border, it would actually now be 212px wide (the 200px width plus 5px padding each side and a 1px border each side). What most sane people would hope happened would be that the 200px width on the element would include the padding and borders.

Thankfully, the latest iterations of CSS have provided a way to make this work sensibly via the box-sizing property.

I like to set this box-sizing property globally so that my entire stylesheet uses it by default and the way I do that is by inserting the following at the very top of my stylesheet:

html {
   -webkit-box-sizing : border-box;
   -moz-box-sizing : border-box;
   -ms-box-sizing : border-box;
   box-sizing: border-box;

*, *:before, *:after {
   -webkit-box-sizing : inherit;
   -moz-box-sizing : inherit;
   -ms-box-sizing : inherit;
   box-sizing: inherit;

This basically just sets the global HTML box-sizing and then tells all other elements to inherit it. The webkit, moz and ms prefixes should take care of a lot of older browsers but bear in mind that very old browsers may not support the box-sizing property.

Note that margins still add to the size of the box but this makes sense because margins are outside the box whereas borders and padding are inside it.

Leave a Reply