Thursday, August 30, 2007

PNG Transparency in Internet Explorer 6

In Internet Explorer 6, the background of transparent PNG files shows up as gray instead of transparent. More modern browsers such as Internet Explorer 7, Firefox, and just about every other browser support transparency for PNG files. However with about 30-50% of people still using Internet Explorer 6, many developers still need to have backwards compatibility with IE6.

Even though IE6 does not support transparent PNG it does have a workaround by using the AlphaImageLoader filter. The AlphaImageLoader is part of a collection of filters that are Internet Explorer specific. I do find it odd that the alpha loader is not enabled for all png files because many workarounds use the filter on all PNG images regardless.

A filter is a cascading style sheet property that works with Internet Explorer 5.5 and beyond. I've seen a couple of different implementations of this workaround but the one that I have found to work the best is PNG Behavior from WebFX. A SugarCRM based website that I worked on used this workaround and it worked out quite well.

Basically this workaround uses yet another Internet Explorer specific feature known as behaviors. Behaviors have never really caught on which is a good thing in my opinion because it is an Internet Explorer specific feature so it does not play nice with other browsers and playing nice is important to me. However behaviors can occasionally be used to patch Internet Explorer so it behaves more like other browsers. A behavior is also a CSS property that among other things allows you to attach a JavaScript function to property change events. This property change event can attach the AlphaImageLoader filter to just the img tags that have src attribute as a png file by using JavaScript to do more advanced things than you could do with CSS alone. For all of the details see WebFX's PNG Behavior. One thing to note is that you will need to set the height and width of all image that are png files or the image will not show when using this technique.

The one difference that I have added was a conditional comment that makes it so that this style would only get applied in IE 6

<!--[if IE 6]>
<style type="text/css">
img, .png_input_image_button {
   behavior: url("");

You can also attach this style to input image buttons or any other html tag that use src as the attribute for its image.