Take a cardboard box.

Measure its width and height.

Put something in it. Om Nom for example.

Add some padding.

Now measure that box again.

Guess what? It’s still the same width and height!

Now then, what if we tried this in HTML and CSS? Today?

For the record, today is 2012. We’re in the midst of a rapidly evolving web that has brought us hardware accelerated 3D transforms, webGL shaders, audio processing, gamepad support, notifications, offline local SQL storage, mouse pointer locking and laserbeams that can destroy entire planets.

With all that artillery in place, let’s make a box, give it a certain width and add some padding.

We specify a box with a width of 100 pixels.

#box { width: 100px; }

Saying our box is 100 pixels wide is like saying our box is 100 pixels wide and it kindof means that “OUR BOX IS 100 PIXELS WIDE”. That’s 100 pixels. Wide. 

Now add a ten pixels of padding inside.

#box { width: 100px; padding: 10px; }

Measure the box again. Guess what? It’s 120 pixels wide.

Jeff Kaufman’s post “The Revenge Of the IE Boxmodel?" came at the perfect timing and reminded me to stop going at this the hard way and adopt the old IE box model in a similar fashion that giveupandusetables.com has been the pragmatic programmer’s best friend over the advice of many white-bearded committee members.

All you need is this:

* { box-sizing: border-box; }

Or, as Paul Irish recommends

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

And BAM! Our box is 100 pixels wide. We’re in sense-making mode again. The one that the loving people at Microsoft came up with back in 1997. Back when IE was bashed at for doing their own browser enhancements (which is deemed perfectly normal for other browser vendors for many years now).

To get a compatibity overview of how box-sizing is supported in different browsers, you could also check HTML5Please

Today I have switched to the border-box model for a real project I’m working on for a real client with a really big team. Already it has saved me loads of stupid calculations (“okay, so the box is 496 pixels wide and there’s 18 pixels padding, and …”) and I wish I had done this 10 years earlier. 

So here’s my advice. Stop using todays box-model and party like it’s 1997.


3 notes

  1. ipaulo-reloaded reblogged this from mrtnkl
  2. mrtnkl posted this


blog comments powered by Disqus