Working around flickering background images in Internet Explorer

by Alexander Limi last modified Dec 30, 2008 03:02 PM

If you try to use a class in CSS that puts an image in the background of a link, you may discover that hovering over it makes it flicker if you have caching in Internet Explorer turned off. Here's how to work around it.

This is a bug in Internet Explorer that manifests itself if you are running the browser without caching turned on. Internet Explorer will get the image every time (!) you hover over a link with a background image, and this leads to flickering when a user hovers over the link with the mouse pointer.

The way to fix this bug is to place a background image on the element surrounding the actual link element.

Code example using Plone's autogenerated content type icon classes:

 <span class="contenttype-folder">
     <a class="visualIconPadding"
        href="#">
     This is a link
     </a>
 </span>

This uses the class contenttype-folder, which is a simple class with a background image on it, and the visualIconPadding class which simply adds some padding on the left side of the link, so that the icon isn't obscured by the link text.

Now the image doesn't flicker when you hover over the link anymore.

So why is this better than simply including the image in the HTML code with a normal image tag? It removes a semantic element from the document (much nicer for accessibility reasons, blind people don't have to navigate through lots of elements that are merely visual decoration), and it allows you to easily override the image on a site-wide basis — should you need it later.

Plone uses this technique on all its elements with icons attached.

Here are how the CSS classes look like, for the curious:

 .contenttype-folder { 
     background-image: url(document_icon.gif); 
     background-repeat: no-repeat; 
     background-position: 0% 50%;
 }

 .visualIconPadding {
     padding-left: 18px;
 }