Placing elements side by side into a layout is an everyday task in the life of a front end developer. Avoiding positioning the element absolutely, I need to choose between the floating way or, more interesting, the
display: inline-block way.
I really love the latter technique, because it gives me the possibility to not mind about clearing the floats, neither with the clearfix hack, nor with the
overflow: hidden rule.
The only drawback of this technique was the space created between elements: some 4 pixels gap very annoying. In a post on the sublime Css tricks blog, I found a very clever solution to fight this unwanted space: setting a font-size value of 0 to the parent element.
Let’s say we have a navigation menu, like this:
you’ll obtain your voices standing side by side. By giving the
nav element a font-size of 0, you erase the gap, but you’ll need to set a proper font-size to the
a elements, because they inherit the ancestor’s font-size. Any prob? Nope.
The problems rise when you’re in a responsive context: you give to the
a elements a font-size value of
1em, because you want them to be proportional and not fixed. Well done, but the
em measure is relative to the ancestor’s one, so 1 x 0 = 0. Ugly.
Wait a minute and don’t despair: there’s an awesome solution brought to you by a new CSS3 unit, the
rem. Quoting from snook.ca:
The rem unit is relative to the root—or the
html—element. That means that we can define a single font size on the
htmlelement and define all rem units to be a percentage of that.
So, there you go: be free to set your font-size to 0 to avoid the gap between elements and use the rem to the a elements, especially if you’re in a mobile context, because IE prior to 9 don’t support it (but you can fall back to pixel measurement).