Explain Codes LogoExplain Codes Logo

A space between inline-block list items

html
responsive-design
css
best-practices
Nikita BarsukovbyNikita Barsukov·Jan 29, 2025
TLDR

Remove spaces between inline-block list items by applying font-size: 0; to the <ul> parent element and then restore the font-size on <li> child elements:

ul { font-size: 0; } //Gets rid of those "invisible" gaps (like a CSS ninja!) li { display: inline-block; font-size: 16px; } //Brings back the readable goodness
<ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul>

Thanks to font-size: 0;, whitespace collapse in the ul element magically zaps gaps, ensuring flush fitting li elements.

Unwrapping the mystery

When inline-block is applied to elements, whitespace in HTML seeps in, altering our layout. This rendering behavior is due to the fact that browsers view whitespace in HTML source code as a single space character in the layout.

Strategies to combat whitespace

Don't let the effects of whitespace ruin your inline-block styling. Employ these handy strategies:

  1. Exile HTML Whitespace:
    Be a minimalist, don't leave any space, newline, or characters between the li tags.

    <ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul> //Neat and without spaces (like canned sardines!)
  2. Whitespaces in Witness Protection:
    Better yet, hide the whitespace in plain sight. Make use of comments.

    <ul> <li>Item 1</li><!-- --><li>Item 2</li><!-- --><li>Item 3</li> </ul> //Spaces? What spaces? 😉
  3. Ballroom dancing your elements:
    A negative letter-spacing on the parent will make your elements dance closer. Like a polite dance partner, reset it on the children elements.

    ul { letter-spacing: -4px; } // Get a little closer... li { letter-spacing: normal; } // Normal dancing distance restored!
  4. Switching the display techniques:
    The world of CSS styling isn't limited to inline-block. Techniques including float: left; or display: inline; on the li elements could also be the solution to your spacing issues (just keep an eye on your overall layout!)

The importance of consistency and further tweaking

Consistency is the key to proper styling. The clever trick of font-size: 0; requires a reset of the font size for list item text. Else, you might be left with a highly sophisticated, invisible font (007 would be proud, but your users won't be!).

The era of Flexbox and Grid

Feeling adventurous? The modern era offers CSS flexbox or grid - powerful alternatives to conquer similar layouts sans the whitespace nuisances.

Embracing all device screens

Your users are wielding screens of all sizes. If your list items house interactive content, ensure that they are easily clickable or tappable, playing nice with all devices.

Accessibility - a non-negotiable

The styling trick of font-size: 0; might have impacts beyond the visual. Always use accessibility tools to make sure the changes do not hamper the usage for any of your users.