skip to content

Fixing Whitespace Between Inline Elements


I was messing around with inline elements the other day and stumbled upon a minor annoyance. You see, a series of inline-block elements with no formatting applied, will have spaces in between them.

HTML

<section>
    <div>One</div>
    <div>Two</div>
    <div>Three</div>
    <div>Four</div>
</section>

CSS

section div {
    padding: 10px;
    background: #ca3e47;
    display: inline-block;
}

This will result in the following:

One
Two
Three
Four

Notice the spaces? Normally you'd want the elements to stay flush against each other to avoid awkward, unclickable gaps.

Luckily there are a few ways to get around this.

Remove the spaces

<section>
    <div>
    One</div><div>
    Two</div><div>
    Three</div><div>
    Four</div>
</section>

or

<section>
    <div>One</div
    ><div>Two</div
    ><div>Three</div
    ><div>Four</div>
</section>

or by inserting comments

<section>
    <div>One</div><!--
    --><div>Two</div><!--
    --><div>Three</div><!--
    --><div>Four</div>
</section>

All of the above will result in the following:

One
Two
Three
Four

While none of these solutions are elegant, they get the job done.

Negative margin

Another solution is to add negative margin the elements, thus compensating for the space.

section div {
    display: inline-block;
    margin-right: -7px;
}

The above will result in the following:

One
Two
Three
Four

Omit the closing tag

With HTML5 we no longer have to add closing tags. While this method will remove the unwanted space, it may introduce other awkward problems.

<section>
    <div>One
    <div>Two
    <div>Three
    <div>Four
</section>

The above will result in the following:

One
Two
Three
Four

Set the fontsize

section {
    font-size: 0;
}
div {
    font-size: 16px;
}

The above will result in the following:

One
Two
Three
Four