Closing the gap between list items in IE

A long-standing bug in Internet Explorer is the gaps it likes to insert between list items that contain block level elements, if there is any whitespace between the list items in the markup. You have probably seen it in action more times than you want to.

This bug was thought to have been fixed in IE 7 RC 1, and perhaps it was. That doesn't really matter since the release version of IE 7 still suffers from it in certain circumstances. Just in case you're looking for something that will fix this problem in both IE 6 and IE 7, I wanted to share this piece of knowledge. I originally thought this would soon be obsolete, but unfortunately that does not seem to be the case.

Let's say you have a nice list of links marked up like this:

  1. <ul>
  2. <li>
  3. <a href="/">List item 1</a>
  4. </li>
  5. <li>
  6. <a href="/">List item 2</a>
  7. </li>
  8. <li>
  9. <a href="/">List item 3</a>
  10. </li>
  11. </ul>

You want the links to display below each other, so you use the following CSS:

  1. ul {
  2. margin:0;
  3. padding:0;
  4. list-style:none;
  5. }
  6. li {
  7. margin:0;
  8. padding:0;
  9. }
  10. li a {
  11. display:block;
  12. padding:0.5em;
  13. background:#ddd;
  14. }

The result will be a vertical list of links with large gaps between them in Internet Explorer up to and including IE 7 beta 3, and smaller gaps in the release version of IE 7. There should not be any gaps.

One suggested fix is assigning a width to the links. I don't like doing that since I prefer controlling their width with their containing element. Setting their width to 100% doesn't work either since in most cases a bit of padding will make the links easier to hit.

I've found that the following trick will make both IE 6 and 7 behave (wrapped in conditional comments here - move to your IE bugfix stylesheet before use):

  1. <!--[if lt IE 8]>
  2. <style type="text/css">
  3. li a {display:inline-block;}
  4. li a {display:block;}
  5. </style>
  6. <![endif]-->

Note that the declarations need to be in separate rules.

That's it. No more gaps in IE 6 or IE 7.

Update (2006-10-20): I just noticed that there are cases where the bug will appear in the release version of IE 7. I'll update this article with the details ASAP, hopefully later today.

Posted on October 16, 2006 in Browsers, CSS