Removing The Gap Between inline-block Elements

November 29th, 2015 - Posted by Steve Marks to (X)HTML / CSS, Web Development.

If you’ve ever had a set of elements in your HTML that have the CSS display property set as inline-block you’ve probably come across the problem where you end up with a 1px gap between them.

Lets look at an example of this where we will use an unordered list:

HTML:

<ul>
    <li>List Item 1</li>
    <li>List Item 2</li>
    <li>List Item 3</li>
</ul>

CSS:

ul {
    list-style-type:none;
    margin:0;
}
ul li {
    display:inline-block
}

Although the above will place the list items side by side, you’ll be left with an annoying gap between them.

The Solution

The issue arises because it is taking into account and showing the whitespace in your code.

There are a number of solutions to this which I’ll explain here:

Solution 1

The first solution is to place all of the list items onto a single line:

<ul><li>List Item 1</li><li>List Item 2</li><li>List Item 3</li></ul>

Although this works, it’s actually my least preferred method as it makes the code very difficult to read and work with.

Solution 2

An alternative to the above is to remove the white space, whilst maintaining the formatting, through the use of HTML comments:

<ul><!--
    --><li>List Item 1</li><!--
    --><li>List Item 2</li><!--
    --><li>List Item 3</li><!--
--></ul>
Solution 3

This final solution works by modifying the CSS only and can be done through the use of settings font sizes like so:

ul {
    list-style-type: none;
    margin: 0;
    font-size: 0;
}
ul li {
    display: inline-block
    font-size: 16px;
}

See how we’ve set the font size to zero on the parent element? Although this, in my eyes, is the cleanest solution, annoyingly there are browsers that don’t 100% fully support this (yet) so use at your own risk.

For now we’ll continue to use the second solution as it maintains code readability. If there are any other solutions you know of that solve this please leave a comment below.

Tags: ,
This entry was posted on Sunday, November 29th, 2015 at 10:59 am by +Steve Marks and is filed under (X)HTML / CSS, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first