The PNG image format is becoming more and more common on the web, and for good reason. It is an open standard that does not require payment of royalties, and it has some cool features that other formats do not. This article is about PNG’s transparency and alpha-blending features.
Transparency is useful when you want to create an image that blends into whatever it is placed on top of. You can sort of do this with transparent GIFs, but they do not support alpha-blending. This means that you can’t have a gradual change from the image colors to the background color. See the two images below. They are identical except for their format. Notice that the drop shadow in the PNG file blends into the background nicely, while the GIF shadow requires a matte color.
Ok, PNGs are great. So what is the real reason for this article? Well, when it comes to displaying PNGs with blending in the browser, things are not so simple. Most modern browsers support this inherently. IE 7 and 8 (and maybe 9?) support it. Firefox supports it, as does Opera and Safari.
Notice that I left out one key browser: Internet Explorer 6. IE6, even though Microsoft no longer supports it, is still in use on a lot of Windows systems out there. In the corporate world it doesn’t seem to want to go away. And IE6 does not support alpha-blending in PNGs.
There are lots of solutions out on the web for getting around this issue, and they all involve the AlphaImageLoader filter. This comes straight from the Microsoft Support web site:
<DIV ID="oDiv" STYLE="position:absolute; left:140px; height:400; width:400;
src='image.png', sizingMethod='scale');" >
If your HTML looks like the above html and the styles are inline, then this works great. But if you use classes to style your web elements in a reusable way, then there is a problem: the
src attribute for the filter is relative to the page that the class appears on. Let me repeat this. The image has to be a path relative to the page that the class appears on. This means that you can’t use the same style on different pages that are in different levels of your web site. And the CSS file has to be in the same directory as your html file(s).
One solution to this issue is to use absolute paths in your CSS file. But this can be problematic as well, especially if you don’t have full control over where your html files are located. Until recently, this is precisely what I was doing. But lo and behold after doing some more research I found a better way in the comments of this page!
It involves a feature of IE that I was not aware of, the behavior tag. The tag supports adding a script expression which is used to grab the absolute source of the image at run time by the browser.
Here is an example on how to use this:
this.src = this.src ? this.src : this.currentStyle.backgroundImage.split('"'),
this.style.background = "none",
this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + this.src + ", sizingMethod='scale')");