
International box-sizing Awareness Day
International box-sizing Awareness Day êŽë š
Itâs February 1st today, which Iâve decided to declare International box-sizing Awareness Day. In honor of, you guessed it, the most humble and undersung, yet awesome and useful CSS property: box-sizing
.
The date corresponds to Paul Irishâs post where he introduced the concept of using it on every single element on the page. Weâve talked about it around here a few times as well.
Here it is, in all itâs glory:
*, *:before, *:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
Note
You might also consider having box-sizing cascade with this technique. The box-sizing
property doesnât normally cascade, and you would be forcing it to, but it makes it a lot easier to override at a component level.
The default value for box-sizing
is content-box
, which is what we are overriding here. There is also a padding-box value but⊠kinda useless if you ask me. Weâll get to what this means shortly.
Notice weâre using the *
selector to select all elements, as well as making pseudo elements use the same model, which otherwise wouldnât be selected by the *
selector alone.
Hereâs the browser support situation. -
= âthis version and downâ. +
= âthis version and upâ.
*, *:before, *:after {
/* Chrome 9-, Safari 5-, iOS 4.2-, Android 3-, Blackberry 7- */
-webkit-box-sizing: border-box;
/* Firefox (desktop or Android) 28- */
-moz-box-sizing: border-box;
/* Firefox 29+, IE 8+, Chrome 10+, Safari 5.1+, Opera 9.5+, iOS 5+, Opera Mini Anything, Blackberry 10+, Android 4+ */
box-sizing: border-box;
}
In the fairly near future we wonât need any prefixes at all for it, but I like to just leave that kind of thing to Autoprefixer.
Why all the HOO-RAH?!
It makes working with boxes so super duper much nicer.
When you set the width of an element, thatâs the width that it is. If you set the width to 25%, it will take up 1/4 of the horizontal space available in its parent element. Thatâs it.
Thatâs not always the case. With the default box-sizing, as soon as an element has either padding or border applied, the actual rendered width is wider than the width you set.
The math is bad enough, but when combined with percentages (or any mixed units, really) the result is impossible to do in your head and, more importantly, ends up being some useless number that you canât do anything with.
You might think of it this way: with box-sizing: border-box
the padding and border press their way inside the box rather than expand the box. The result is a box the exact width you set it to be and can count on.
Columns is a particularly useful case, but this comes in useful all the time and becomes one of those things that just makes CSS development better.
Note
Remember to read Paulâs original post which covers some more ground like performance (donât worry about it), jQuery (donât worry about it), and third-party content (easy to fix).