CSS Hackz Series: PNG Fix for Internet Explorer

by Jeff Starr on Wednesday, May 28, 2008 23 Responses

In this CSS Hackz Series article, I outline several solutions for displaying alpha-transparent PNG (a.k.a. PNG-24 format) images in everybody’s favorite broken browser, Internet Explorer. Specifically, IE versions through 6 (excluding IE 5 for Mac) fail to support alpha-channel transparency for PNG images. In these versions of IE, every pixel containing alpha-transparency is displayed with an ugly, flat gray color.

Fortunately, there are plenty of hacks and workarounds designed to “fix” IE’s PNG image-display problem. Unfortunately, every currently available solution requires the use of Microsoft’s proprietary AlphaImageLoader transparency filter 1. Thus, if you need to display translucent PNG images in IE, the solution will inevitably involve the AlphaImageLoader filter until more sophisticated techniques are developed.

General Method

The general implementation of the AlphaImageLoader transparency filter requires three steps:

1. Include an IE-specific stylesheet via conditional comments:

<!--[if lt IE 7]>
	<link rel="stylesheet" type="text/css" href="http://domain.tld/path/ie-specific.css" />
<![endif]-->

2. Within the same directory as the IE-specific stylesheet, upload a transparent GIF file 2 and this .htc file, provided by TwinHelix Designs which contains an excellent implementation of the required AlphaImageLoader function.

3. Finally, add the following “custom extension” to your “ie-specific.cssCSS file:

.png { behavior: url(http://domain.tld/path/png.htc); }

Once in place, this method will enable IE (versions 5.5+/Win) to display transparent PNGs for any PNG images associated with the “.png” class. This method works great for designs containing multiple PNGs as the behavior is applied to all .png-classed images — inline or background — regardless of name or location. For designs using only a few PNG images, the next method is equally effective, and doesn’t require any external files.

Simpler Method

This method replaces the external “png.htc” and transparent GIF files with a small chunk of invalid CSS:

.png {
	cursor: pointer;
	background: none;
	/* filter applies only to IE5+/Win */
	filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true', sizingMethod='fixed', src='http://domain.tld/path/image.png');
}
.png[class] {
	/* [class] applies to non-IE browsers */
	background: url(http://domain.tld/path/image.png) no-repeat;
}
* html .png a {
	/* make links clickable in IE */
	position: relative;
	z-index: 999;
}

Once in place, this chunk of CSS enables IE (versions 5.5+/Win) to display transparent PNGs for any PNG images associated with the “.png” class.

To use this code for background images, edit the image path/name to match your own and ensure that the .png class is included in the markup. For inline images, the second code block (i.e., .png[class]) may not be necessary. Here are a few more potentially useful considerations:

  • For best practice, include this code via conditional comment in an IE-specific stylesheet.
  • Alternatively, you may want to use the * html filter to keep the rules from interfering with other browsers (may affect performance).
  • This method will not work for background images that have been positioned in any way or set to repeat in any direction.
  • If the target PNG images fail to display properly, try replacing the sizingMethod='fixed' parameter with either sizingMethod='crop' or sizingMethod='scale'.
  • The last code block (i.e., * html .png a) is required only if there are links within the target element.

Alternate Method

An alternate approach to displaying transparent PNGs in IE involves placing the following code directly into your CSS file:

* html img,
* html .png {
position:relative;
behavior: expression((this.runtimeStyle.behavior="none")&&(this.pngSet?this.pngSet=true:(this.nodeName == "IMG" && this.src.toLowerCase().indexOf('.png')>-1?(this.runtimeStyle.backgroundImage = "none",
this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.src + "', sizingMethod='image')",
this.src = "transparent.gif"):(this.origBg = this.origBg? this.origBg :this.currentStyle.backgroundImage.toString().replace('url("','').replace('")',''),
this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.origBg + "', sizingMethod='crop')",
this.runtimeStyle.backgroundImage = "none")),this.pngSet=true)
);
}

Of course, you will probably want to include this code via conditional comment and an IE-specific stylesheet:

<!--[if lte IE 6]>
	<link rel="stylesheet" type="text/css" href="http://domain.tld/path/png_fix.css" />
<![endif]–->

A few notes should you decide to go this route:

  • Invalid CSS
  • Works well only for statically displayed images.
  • Requires a transparent 1px-square GIF image.
  • Non-repeating backgrounds should be sized to “crop”, others should be sized to “scale”.
  • As-is, this CSS expression is very resource-intensive, so..
  • USe this.runtimeStyle.behavior="none" to ensure the function is executed only once.

For more information regarding this method, check out the original article at Komodo Media.

JavaScript Method

There are several JavaScript techniques for applying the AlphaImageLoader transparency filter to target PNGs. One of the more popular methods is the SuperSleight method. SuperSleight solves many of the problems typically associated with previously discussed methods:

  • Improved performance — the function can be executed throughout the entire document or only in specified page regions.
  • Clickable links, focusable forms — optional automatic application of position: relative to links and form fields.
  • Automatic sizing method — detects background images set to no-repeat and sets the scaleMode to crop rather than scale.
  • Applied to new content — automatically applied to any newly added content, such as that loaded via Ajax requests.
  • Replaces previous versions — works with both inline and background images, replacing the need for both sleight and bgsleight.
  • Valid CSS — requires no special CSS.
  • Web Standards — complete separation of structure, presentation, and behavior.
  • Unobtrusive functionality — exclusively targets deficient versions of IE.

The downside to this method is that JavaScript must be available in order for it to work. Other than that, the technique is nearly perfect, addressing nearly all of the shortcomings of previous methods. To use this method, download the Supersleight script and a transparent GIF, upload the files to your server, and include the function via conditional comment:

<!--[if lte IE 6]>
	<script type="text/javascript" src="http://domain.tld/path/supersleight.js"></script>
<![endif]-->

..and that’s all there is to it. No need to mess with class names, alternate images, or specific attributes. Supersleight does all the work by traversing the DOM and applying the required filters via pattern matching. Completely unobtrusive!

Other Methods

As mentioned, there are many currently available PNG hacks for Internet Explorer. Here are a few of them:

Let me know of any others that should be added to the list!

Coming Next..

In the next fascinating CSS Hackz Series: The Ubiquitous Clearfix Hack! Stay tuned..

Footnotes

  • 1 As far as I know. If you know of an alternate technique, please let us know!
  • 2 Rumor has it that the transparent GIF file is not needed for CSS background images.

23 Responses
[ Gravatar Icon ]

Dejan Cancarevic#1

thanks for mentioning me

[ Gravatar Icon ]

Perishable#2

My pleasure, Dejan! I only wish I had the time (and stamina) to cover more methods in depth. Yours would have definitely been included. Keep up the great work! :)

[ Gravatar Icon ]

Andreas Stephan#3

Nice sum up!
Just be careful using this “hack”! Especially if you apply it inside javascript using expression, it can slow down the site a lot! If you need many pngs on your site, consider using png8 instead of png32 like described here: http://www.sitepoint.com/blogs/2007/09/18/png8-the-clear-winner/
IE6 won’t display it as nicely of course but you wont need hacks or custom css, AND: IE6 is the new NS4 and thus dying out (hopefully very soon) ;)

[ Gravatar Icon ]

Perishable#4

Hello Andreas! Thanks for the sweet tips. I was under the impression that JavaScript implementations of the AlphaImageLoader transparency filter have much less of a negative impact on performance than do CSS-based expressions. Also, using a script such as Supersleight, it is possible to target specific areas of the page to further improve performance. Nonetheless, I completely agree with you that people should be careful when hacking for IE-PNG support. The whole mess is really dodgy to begin with, and I hold hands and pray along with the untold masses that look forward to the soon extinction of the horrid IE6 browser ;)

[ Gravatar Icon ]

August Klotz#5

I read somewhere that including this CSS code at the very top of an imported stylesheet will enable proper display of PNG-32 translucency in Internet Explorer 6.

[ Gravatar Icon ]

Andreas Stephan#6

@August: Never heard of that before. I doubt that thats true too, otherwise it would be a well-known solution.

[ Gravatar Icon ]

Perishable#7

Yes, that is a good point, Andreas. That technique would be all over the Web in a matter of days if it actually worked. So far, I have only seen one other instance of it (in the comments of a Site Point article on PNG-8). Nonetheless, it wouldn’t surprise me if nobody has actually tested it, so it shouldn’t be shrugged off completely until somebody takes the time to do so (and it won’t be me!).

[ Gravatar Icon ]

jitendra vyas#8

i want to use png without javascript with valid css and html too. then which is best ?

[ Gravatar Icon ]

Jeff Starr#9

@jitendra vyas: unfortunately, all of the “quick-fix” methods (such as the ones described in this article) require JavaScript. Some methods place it in the CSS, and others keep it entirely in an external file. Either case, it’s still JavaScript. IE support of true, alpha-transparent PNG-24 format is just not possible without JavaScript.

[ Gravatar Icon ]

ollie#10

Thank you so much, I searched for hours to solve an issue relating to a collapsible/animated accordion and this post solved the issues. It was clear and concise and worked really well.
Ollie

[ Gravatar Icon ]

Jeff Starr#11

My pleasure, ollie –thanks for the positive feedback! :)

[ Gravatar Icon ]

CSSJockey#12

Hi, I tried opening this site in ie6 and I see there are some issues with it. Please check..

[ Gravatar Icon ]

Jeff Starr#13

@CSSJockey: Hmmm.. I just checked and it looks like everything is appearing as intended. Did you happen to catch the large red text at the top of every page that says:

ATTENTION: Perishable Press no longer supports old versions of Internet Explorer. Please upgrade your browser or switch to something better, like Firefox, Opera, or Safari.

Hopefully that explains the situation. Let me know if you need additional help with this.

[ Gravatar Icon ]

CSSJockey#14

Hi Jeff, The page is displayed without any styles with a plane white background.
I have uploaded a screen shot here

http://www.cssjockey.net/images/pngfix-not-working-ie6.jpg

I am trying hard to find a working pngfix for ie6 as a lot of free goodies and wordpress themes are in pending state to be released on CSSJockey.com.

Any help regarding this issue will be highly appreciated.

Regards,
Mohit Aneja - CJ

[ Gravatar Icon ]

ollie#15

@CSSJockey

Hi,

I used the PNGfix for ie6 on this site, and all works well in ie6:

http://www.transpo.dbschenker.com/

Ollie

[ Gravatar Icon ]

Jeff Starr#16

@CSSJockey: Not sure if I’m communicating effectively enough here.. If you look at the top of the screenshot you posted and read the large red text, it clearly explains why Perishable Press looks “plain” in Internet Explorer 6. This notice appears on every page on the site when viewed with IE6, so I am finding it difficult to imagine how you may have missed it there, in my previous comment, and in your screenshot. Further, with a name like “CSSJockey”, I would expect that the whole IE6-support thing would be old news for you.

[ Gravatar Icon ]

Jeff Starr#17

@ollie:

Yes, PNGfix is good and so is Drew Diller’s DD_belatedPNG @ http://www.dillerdesign.com/experiment/DD_belatedPNG/

Cheers,
Jeff

[ Gravatar Icon ]

CSSJockey#18

@Jeff
I have tried a lot of fixes and workarounds, however I am not able to find or create any script which supports everything like background, hovers etc. Not sure why but IE6 crashes with most of the fixes.

I read the note there but if your own website is not supporting ie6 what’s the idea of preaching about fixes that you can’t implement with your own setups.

If we talk about market share of web browsers IE6 is currently used by 20 to 25 percent of the people online.

I am looking for a fix to implement on our WordPress Themes to be released on CSSJockey.com not for my own website. And I cannot simply write a note that this theme will not work on ie6. That would be stupid i believe.

If you open CSSJockey.com in IE6 you won’t find much difference in the layout and design.

[ Gravatar Icon ]

Jeff Starr#19

@CSSJockey:

I read the note there but if your own website is not supporting ie6 what’s the idea of preaching about fixes that you can’t implement with your own setups.

If you read the note and actually understood it, why then, after seeing the web pages, reading my comment, and even posting a screenshot, do you make a statement that suggests you have absolutely no idea about what’s going on, as demonstrated in your next comment:

The page is displayed without any styles with a plane [sic] white background.

And now you have the audacity to act like you actually understood the reason for the unstyled pages the whole time? What, do you just like wasting my time or insulting my intelligence or both? If you did understand what was going on, then why waste my time with a screenshot in your second comment? Why not just argue against my clear decision to not support IE6 to begin with?

As if that weren’t enough, your third comment then goes so far as to reprimand me for my decision not to support IE6? WTF is up with that, dude?

You then go on to insult me further, and for no apparent reason, by saying:

I read the note there but if your own website is not supporting ie6 what’s the idea of preaching about fixes that you can’t implement with your own setups.

Before stuffing your foot in your mouth by making such ignorant statements, you had better do your homework. I have been designing websites and writing web-dev articles since you were in diapers. Check the Archives. I have written extensively on supporting many aspects of IE6 and have developed countless sites and themes that fully support that terrible browser.

My decision to drop IE6 support for my personal blog design is one of principle, adhering to the belief that IE6 is an outdated, inefficient and even dangerous browser that should no longer be used. There is actually an entire movement of people who believe that we, as a community of designers and developers, need to begin the process of eliminating IE6 by dropping support for that hideous browser. This is exactly what I have done with my current design.

By the way, the script you are looking for is available from Dean Edwards. Check it out, should be exactly what you are looking for.

[ Gravatar Icon ]

simple websites#20

Thank you so much, I searched for hours to solve an issue relating to a collapsible/animated accordion and this post solved the issues. It was clear and concise and worked really well.

Trackbacks / Pingbacks
  1. Definitive Guide to Taming the IE6 Beast - Programming Blog
  2. Полное руководство по укрощению IE6 | Очередной блог фрилансера
  3. Transparent PNG 24 Images with Internet Explorer 6 for Beginners | Resources for Web Development Students @ Robin's Blog
Comments are closed for this post

If you have or need further information, contact me.



Attention: Do NOT follow this link!