CSS's undersung property: box-sizing

Posted on February 09, 2017

Here is a little CSS snippet we can apply to *all elements which will make our lives infinitely easier:

html { box-sizing: border-box; } *, *:before, *:after { box-sizing: inherit; }

CSS box-sizing explained:

Ever since the introduction of the CSS box model (CSS Level 1), padding and borders have been considered an addition to the element they are properties of. For example, if you declare a width of 20% on an element and then add 25px of padding it becomes 20%+25px wide. This can cause major headaches when developing and makes responsive CSS a nightmare.

As from CSS3 (CSS Level 3) box-sizing changes everything! It tells the browser to render the box model using the 'IE box model', used by Internet Explorer in 'quirks mode', where height and width determine the height and width including padding and borders. Therefore, if you set an elements width to 20% and add 25px of padding it will cut into the element rather than adding to it.

Browser support:

Thankfully, it turns out that box-sizing is pretty well supported throughout all major browsers. Some browsers require the -moz- prefix and iOS needs a -webkit- prefix but all the rest don't. For a more detailed analysis check out the awesome caniuse.com support table.

Further reading:

1.W3.org CSS3: box-sizing

2.CSS-Tricks: box-Sizing

3,Controlling width with CSS3 box-sizing

4.Can I Use? Support table

5.MDN box-sizing