The inline-block CSS property is in many respects quite mighty. Unfortunately it has also it's drawbacks. E.g., the following: Suppose a navigation list

<ul id="nav">
  <li>...</li>
  <li>...</li>
</ul>

where the list items are inline blocks:

#nav li {
  display: inline-block;
}

Note the white space between the list elements. Now, since inline-block converts the list items to inline elements, the white space begins to matter and is displayed as a single space between the items.

The Question: How do you deal with this problem? Any cool technique? (Besides using blocks and float:left...)

I've come up so far only with two possibilities: Removing the white space alltogether or introducing superfluous comments:

<ul id="nav"><!--
  --><li>...</li><!--
  --><li>...</li><!--
--></ul>

which is really nasty.

2 answers

2
points
This was chosen as the best answer

It seems that what you really need is white-space-collapse: discard, but, as far as I can tell, no browser implements that property even in vendor specific rules.

The best result I managed was to set a negative margin on the elements. By trial and error I determined the width of a space to be 0.25em (for my default font, in my default browser - dunno how universal that is):

#nav li {
    display: inline-block;
    margin-left: -0.25em;
}

Works OK in Firefox and Safari, get some slight spacing at different zoom levels.

Answered over 7 years ago by Rob Crowther
  • I had the same idea, but was able to test it on IE7 and 8 on Windows 7. IE7 seemed to have problems with display: inline-block, but was fine with display: inline; whether hasLayout was triggered or not. I used a border for the list elements first which resulted in those slight spacing issues you mentioned. Setting a background-color alone worked here. Polyfragmentiert over 7 years ago
  • Yeah, IE7 doesn't support inline-block so I didn't worry too much about it - have to stick to floats anyway there. Rob Crowther over 7 years ago
  • I read about white-space-collapse a long while ago and forgot about it. Thanks for bringing it back to mind. The trick with the negative left margin is cool, too. Boldewyn over 7 years ago
0
points

I know this is an old post, but I thought I'd contribute another idea.

The white-space is determined by it's parent containers font properties, so why not set the ul#nav's font-size to 0 and explicitly specify a font-size for the li's?

ul#nav
{
     font-size: 0;
}

ul#nav li
{
     font-size: 14px;
     display: inline-block;
}

Firefox 4, Chrome and IE8+ seem to like this. The only thing I'm not too keen on is by setting the ul to font-size: 0, I can't use relative measurements for the li's.

I'd be interested on hearing other people's thoughts on this idea.

Answered over 6 years ago by Jay Vincent
  • Have a read of http://www.lifeathighroad.com/web-development/css-web-development/inline-block-whitespace-workaround/ and the blog post it links to. Rob Crowther over 6 years ago