A space between inline-block list items
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:
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:
-
Exile HTML Whitespace:
Be a minimalist, don't leave any space, newline, or characters between theli
tags. -
Whitespaces in Witness Protection:
Better yet, hide the whitespace in plain sight. Make use of comments. -
Ballroom dancing your elements:
A negativeletter-spacing
on the parent will make your elements dance closer. Like a polite dance partner, reset it on the children elements. -
Switching the display techniques:
The world of CSS styling isn't limited toinline-block
. Techniques includingfloat: left;
ordisplay: inline;
on theli
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.
Was this article helpful?