Friday, March 14, 2008

Background images not showing in IE6

The scenario: You're trying to change the background of the element by clicking on it. You write some quick code:

/*css*/
#my-element { background:url(expanded.gif) no-repeat; height:10px; width:10px; }
#my-element.collapsed { background-image:url(collapsed.gif); }

//js, using Ext
Ext.onReady(function() {
  var e = document.getElementById("my-element");
  e.on("click", function() {
    e.toggleClass("collapsed");
  });
});

The problem: IE6 makes the background image disappear when you click on the element. What gives?

Solutions: There are several ways to fix this problem:

  1. Use sprites. Instead of having two separate images, create a single image that combines both, and then set the background-position via the class name.

  2. Add the second background image to the parent element. This isn't ideal, but if for whatever reason you can't have sprites, the second background will show if the background in your element fails to render. The key here is that the second background must be hidden behind the initial background of your element.

  3. And the crazy hack I found today. In case you haven't seen the pattern, only images that are computed as a style parameter on page load will work properly.

    So if you can't use sprites and you can't use your parent element as a fallback, you can simply apply the background to anything that gets its styles computed on page load. Yes, that means you can do stuff like this:

    html {background:url(cacheme1.gif) no-repeat -5000px;}
    meta {background:url(cacheme2.gif) no-repeat -5000px;}
    script {background:url(cacheme3.gif) no-repeat -5000px;}
    

No comments:

Post a Comment