{box-sizing:border-box;} – The Box Model

We’ve all done it – set a fixed width on a div to say 200px, then later we need to add 10px padding and a 1px border, our div is now 222px wide.

Its a weird quirk but we’ve learnt to live with it.

I’m working on a SharePoint project at the moment and got stumped on a floating 3-step wizard type upload panel.

The panel is activated by a link in the main navigation, it operates like a click activated drop down menu. The problem was that the wizard needed to have padding, but also needed to be 100% wide.

Insert weird box model, what happened was that the padding added to the overall 100% width, meaning it would run off screen and would have caused horizontal scroll bars.

I tried a variety of different percentages, but no matter what, none of them sat flush to the edges of my screen, which means it could look worse on other peoples screen resolutions.

{box-sizing:border-box;} to the rescue! this is an amazing selector and I’ve heard about it before in the past, but have never had a use for it till now. Some people swear by it and think you should use it for all your elements. As great as it is, the browser support isn’t that great (IE8+ and Firefox still needs the -moz- prefix) and I think it should be used where needed. It works great with fluid layouts, or anything that uses percentages.

So what does it do? it basically gives you the box model you want. If you tell a div to be 200px wide then it’ll give you a 200px wide div regardless of the padding and borders you add.