Transparent PNGs in IE

There are lots of ways to achieve working transparent PNG's in IE (Microsoft Internet Explorer). I have found that none of these have succeeded in making life really easy when doing the dreaded cross browser testing and debugging. Until now that is. Today I discovered DD_belatedPNG by Drew Miller. An awesome library with a really strange name :)

With some simple JavaScript you can have transparent PNG's in a matter of seconds. All it takes are 3 steps:

  1. Download and install the library
  2. Add some classes in HTML
  3. Write some really simple JavaScript

1. Download and install the library

Download the minified library and place it in a folder in your site somewhere. Then stick this in the <head> of your HTML page:

  <!--[if lt IE 7]>
 
    <script type="text/javascript" src="scripts/DD_belatedPNG_0.0.8a-min.js"></script>
 
  < ![endif]-->

2. Add some classes in HTML

This is where life gets simple. Any HTML element that is a transparent PNG, or anything that has a transparent PNG as a background image, needs to be targeted by this plugin. The quickest and easiest way I've found of doing this is to add my own class of "pngfix" to every HTML element that needs fixing in IE. This way all elements are quickly and easily identified.

<img class="logo pngfix" src="../images/logo.png"/>
 
<a href="about.html" class="pngfix">About</a>

3. Write some really simple Javascript

This is where the magic happens. The DD_belatedPNG library requires that you call a function and pass it the elements which contains the transparent png as comma separated CSS selectors:

DD_belatedPNG.fix('#logo, #nav li');

You can see that this list could quickly grow and become difficult to manage:

DD_belatedPNG.fix('#logo, #nav li, #header, #footer .banner, #nav li a:hover, #sidebar div h3 span');

My solution was to use just one selector. Give every element that needs PNG fixing in HTML a class of pngfix and then use that class in the JavaScript.

window.onload = function() { 
 
  // Execute the fix function, passing in the appropriate containers of transparent PNGs 
 
  DD_belatedPNG.fix('.pngfix');
 
}

I placed this in its own JavaScript file and then called that from within the condition comments in the headers:

 <!--[if lt IE 7]>
 
   <script type="text/javascript" src="scripts/DD_belatedPNG_0.0.8a-min.js"></script>
 
   <script type="text/javascript" src="scripts/pngfix.js"></script>
 
 < ![endif]-->