Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
display inline-block 0 space hack

This is a pretty simple hack, but one you don't commonly think of. When using display: inline-block there is a default 4px of space that shows up in the rendered output of the browser. This can be a real layout issue depending on how you are spacing your content blocks. And we really like display: inline-block because it doesn't come with the baggage that floats do. But that space?

What's annoying is that the space is negated when the HTML elements don't have space between them. For example:

<div class="block"><div class="cube">hello</div><div class="cube">hello</div><div class="cube">hello</div><div class="cube">hello</div><div class="cube">hello</div></div>

This example will NOT create the 4px of space between the elements. Typically your code will be exactly like this when minified for production, but it's a real pain in the ass when in development as you are typically not minifying your code in that environment. And if you are not minifying your HTML in production, then you are really in need to have a solution for this that works.

What to do?

There is the -4px hack, but I have never really been a fan of that. You could manually manipulate your HTML elements to remove the space, but that is crappy too.

What's interesting about this problem if you think about it is that this space is dependent on the font size being set to a value that renders space. So, set the font-size to 0.

The trick with this is that you need to set the font-size to 0 on the outer container. That means that the internal blocks will be set to 0 as well. To fix that, set the internal blocks to font-size: 1rem. But there is the IE8 issue with that. What sucks there is that you basically have to use a pixel size now because trying 16em is like saying 16 * 0 and that's 0 again.

The Gist

Here is a SassMeister gist you can play with to see for yourself.

.block
.cube hello
.cube world,
.cube how
.cube are
.cube you?
// ----
// libsass (v3.1.0-beta)
// ----
.block
width: 100%
height: 100px
background-color: orange
font-size: 0
.cube
$cubes: 5
width: 100% / $cubes
height: 100%
background-color: blue
display: inline-block
font-size: 1rem
color: white
text-align: center
line-height: 100px
.block {
width: 100%;
height: 100px;
background-color: orange;
font-size: 0; }
.cube {
width: 20%;
height: 100%;
background-color: blue;
display: inline-block;
font-size: 1rem;
color: white;
text-align: center;
line-height: 100px; }
<div class="block">
<div class="cube">hello</div>
<div class="cube">world,</div>
<div class="cube">how</div>
<div class="cube">are</div>
<div class="cube">you?</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment