The Box Model, Box-Sizing & You
I Promise This Won't Be Boring
The "Box Model" is the model all websites are built around. In websites, everything is inside other boxes. The
<body> tag is inside the
<li> tags are inside
<ul> tag, etc. Positioning, floating, flexing, border width, padding or margin can move these boxes away from each other and can push the content around, but they are still always inside something else.
Now my weird picture above makes a little more sense, eh?
Boxes Are Fun
Let's say I have a box, and it's 400px by 400px and it's background colour is blue.
Pretty simple. Now let's put a slightly smaller red box inside it.
Our red box is right on the edge of the blue box and it looks weird. We could center it with margin, but let's just add some padding to the blue box instead.
That looks better. Now if we -- wait. Is that blue box bigger than before!? Yes, it is, due to the padding we just added. We added 50px of padding to the top, right, bottom and left sides of the box and now our box is 500px by 500px.
What do you mean, duct tape won't fix it?
Padding and border have this effect on element in CSS. It makes sense since you're adding padding "inside" the box. Not everybody wants this though. To "fix" this, you'll have to make your box smaller than what you want, like so:
But that's weird. We have two boxes of the same height and width but they're different sizes.
So... what if we used percentage instead?
Because of padding, now this 100% element is larger than 100%. We couldn't subtract pixels from percentages very easily prior to CSS3, but with calc now we can. calc can do simple math problems and come up with a solution for either the height or width of an element.
While using calc for something like this works, it's totally overkill. Is there an easier solution?
Box-sizing to the rescue!
CSS has a style in it called box-sizing. This allows you to choose if you want to add padding and border inside or outside the dimensions of the box. By default, all elements are styled with it outside (or content-box). If we switch it to border-box, we'll be able to solve our problem.
(Unfortunately, box-sizing doesn't work in older Safari browsers so you'll have to add one of those damn prefixes again to make it work.)
Bingo! Now it looks great! If you wanted to add it to every element on your site, you'd do something like this:
I use box-sizing on all my sites and it makes styling a thousand times easier. I don't have to subtract pixels from widths and height, nor do I have to use calc to get the computer to do the math for me. I use box-sizing in my CSS reset too.
Do you use box-sizing in your websites? Let me know in the comments below!