How do I display alpha transparent PNGs across all browsers?

Update: This article was written when developers had to whip IE6 into shape. If you’re still coding for IE6, perhaps retraining as plumber might be more advisable?

Many web developers have shunned the PNG image format in the past. For some this has been because of a perceived lack of support for alpha transparency (described formally as alpha compositing) in Internet Explorer. Here are some directions on how you can use alpha transparency successfully across all browsers – and specifically IE 6 for Windows.

The first block of CSS sets a background image on an element with the id “demo1″ (typically a div, span or img) for all browsers. This works fine for everything else, but doesn’t work with IE prior to version 7.

The second block targets just these “broken” browsers through use of a conditional comment. This second block uses the filter property to set up a proper alpha transparent version of the png. Read more about this here at the MSDN site.

In the following example the CSS above would show the logo.png with alpha transparency as the background to a div:

<divid="demo1"></div>

This next example shows that you can display a png with alpha transparency by targetting a transparent image:

<imgsrc="transparent.gif"id="demo1"alt=""/>

There are plenty of variations of this technique. All the examples above are considered “standards friendly”. This final example shows the same CSS simplified (but not passing validation):

If you are putting the CSS above into an external stylesheet, then be aware that the path to the logo.png when used as the background image is relative to the CSS file, but the path to logo.png when used in the filter is relative to the enclosing HTML file. This can cause some confusion.

On a related note… you should always ensure your alpha transparent PNGs are 32-bit to ensure that they always display the same colour across all browsers (specifically Firefox and IE displayed a 24-bit alpha transparent PNG differently using the technique described here – changing it to 32-bit confirmed this was the case).