CSS

Understanding CSS Box Sizing

Posted on by

The relationship between an element’s width and padding has always been quite annoying in my opinion. You’re off coding your awesome grid, all of your widths measure up to 100%, and you’re looking great. Then, you add some padding in and the whole thing breaks! Here is how the current box model works with padding…

width + padding = rendered width (width of 200px plus 20px of padding equal a width of 240px…yuck!)

This is no good and just makes things frustrating. Using border-box is the solution to this problem. I believe this is how padding should work by default and just make more sense. Instead of the padding adding on extra width, it adds the padding inside of your element rather than tacking it on to the width. So, you can keep your div at a width of 25%, add padding, and not worry about it breaking your grids.

The CSS

CSS


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

This will apply border-box to all of your elements making padding quite enjoyable to use instead of being a pain.

Browser Support

The browser support is actually very good. Box sizing is safe to use with IE8 and up (Full browser compatabilty¬†at MDN). To see box-sizing in ¬†action, I’ve put together a quick CodePen for a demo so you can see the differences and even experiment yourself.

View Demo

Leave a Reply