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:

<ul>
	<li>
		<a href="/">List item 1</a>
	</li>
	<li>
		<a href="/">List item 2</a>
	</li>
	<li>
		<a href="/">List item 3</a>
	</li>
</ul>

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

ul {
	margin:0;
	padding:0;
	list-style:none;
}
li {
	margin:0;
	padding:0;
}
li a {
	display:block;
	padding:0.5em;
	background:#ddd;
}

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):

<!--[if lt IE 8]>
	<style type="text/css">
		li a {display:inline-block;}
		li a {display:block;}
	</style>
<![endif]-->

Note that the declarations need to be in separate rules.

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

Posted on October 16, 2006 in Browsers, CSS