Lately, I’ve seen more people complain about how
display: inline-block is broken. But it’s not. I’ll explain.
Developers often use
display: inline-block as a layout tool in lieu of floats. This can be a good alternative to complex floating and clearing… sometimes.
As an example, let’s say you have 3 child divs you want to stack, left-to-right, inside a container div. The widths of the 3 child divs add up to the width of the container div. So you think, hey, I’ll throw
display: inline-block on them and call it a day. This is what you end up with:
Chaos! Rogue margin between the left and center div! And what the hell does that right div think he’s doing? Go home right div, you’re drunk!
Alright, so here’s what’s happening. When you use
display: inline-block, you’re telling those divs to flow inline, like text. And not just like text, but with text. You know what counts as text? Whitespace. That’s right, the whitespace between your divs is being rendered inline along with them, causing that tiny bit of spacing. Furthermore, those few extra pixels are more than the container div can hold, which is why the right div wrapped to the next line.
While the results may seem odd, the rendering is actually technically correct (which we all know is the best kind of correct).
There are several ways to work around this, but these are probably your three best options.
Option #1: Remove the whitespace from your markup. This cuts straight to the problem, but can leave you with long, unformatted lines of HTML, which is not the greatest feeling.
Option #2: Reduce
font-size to 0 on the container. This makes the whitespace have no width. Just be sure to restore
font-size within the child divs if you have text in them.
Option #3: Don’t use
display: inline-block. Like many CSS techniques, it has its place, but if you find yourself cursing the intended behavior then maybe that’s a sign you’re using the wrong tool for the job. Consider using floats.