Responsive Layouts and Floats with *{ box-sizing: border-box; } (Quick Fix)

I’ve decided to start something new here. I am going to (attempt to) post one short and simple trick I’ve learned that I use every day in my code. I am going to call them, Quick Fix. I know… not really creative. Welcome to my life. What I am going to do is start with fixing a problem I think everyone has when they combine responsive web design and floats or inline-block.

Let’s get to the code. This week’s Quick Fix is a trick I learned over two years ago when I first started doing responsive web design. It surprises me the number of people at conferences that don’t know of this little CSS fix. It’s saved me more times than I can count.

How many times have you wanted to have a two column layout, built with floats or inline-block, where each column is exactly 50% width? Each of the boxes below have these styles:

.floated{
    float: left;
    width: 50%;
}

This set of styles results in something that looks like this. It looks like we intended, but what happens when you add a 1px border, or some padding?

.floated
.floated

My first instinct is to figure out width, divide by 2, subtract 2px and set the width. Unfortunately, that breaks as soon as the screen width changes size by 1px. Not ideal. This situation is the embodiment of this gif:

Peter Griffin hating CSS

So to fix this issue, I present to you the solution:

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

Basically, this little snippet of CSS makes the browser calculate width of the object INCLUDING padding and border, instead of just content, which is the default

.floated
.floated

Compatibility

IE Chrome Safari Firefox Opera Mobile
8+ 9+ 3+ 1+ 7+ Good

(IE6/7 Polyfill)

And that’s it! That will save your responsive designs. Let me know your thoughts/questions below.