Box Sizing: Border Box

If you’re new to CSS, or even if you’ve been around a while, then you understand the frustration of the typical CSS box model. You specify that a box, or a div, will be a certain width in your CSS. You set up all of your column widths and the width of your elements. If you’re not using a certain responsive css framework, then you’ve probably already created your own custom margin sizes between each column. You’ve done a lot of work, and you’ve invested a lot of time into your web design project. Then comes your text. You start to place some text, and realize that you need to add padding to your text in order to give it some breathing room between columns. This throws a monkey wrench into your whole project. Trying to take away the size of the padding from other elements so that all of the calculations work out ends up being a nightmare. Fear not, because there is a simple solution, originally brought to light by Paul Irish, and it works like a charm. It’s called Box sizing: Border box and it rocks! Here’s how it works:

/* Start Border-box */
*, *:before, *:after {
  -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box;
 }
/* End Border-box */

What Box-sizing: border-box Does

Box Sizing: Border Box

Normally, when you add padding to an element in CSS, it adds that padding to the overall size. I don’t know why it was set up that way, it just does, and it’s irritating. This is especially true with all of the calculations you have to make when creating multi-column layouts, etc. Now, when you create a box that you want to be 300px wide, and you give it 30px of padding (that’s a lot of padding), it stays at the width of 300px, even with the padding. This is excellent, and takes the headache out of web design with CSS.

Remember Your Prefixes

This isn’t necessarily for the latest versions of browsers, but with older browsers this still seems to work well, but you still need to include the prefixes, such as moz and webkit. Otherwise, they won’t show up and your site won’t look how you intended. The star means that it is applied to all elements, which keeps everything neat and tidy.

Good Frameworks Already Have Box Sizing: Border Box Built In

I decided to crack open a website that I was working on in Foundation 5, and I did a search for this to see if they’d implemented Box Sizing: Border Box in their css. Sure enough, it was in the foundation.css file that is packaged with their download. I know that I didn’t have trouble with padding when using Foundation, and now I know why. It was right there, close to the top of their main css!

box sizing border box