Cross-Browser Variable Opacity with PNG
periodically, someone tells me about the magic of png, how it's the ideal image format for the web, and that someday we'll all be using it on our sites instead of gif. people have been saying this for years, and by now most of us have stopped listening. sadly, flaky browser support has made png impractical for almost everything; but now, with a few simple workarounds, we can finally put one of its most compelling features to use.
png? what?
the portable network graphics, or png (pronounced “ping”), image format has been around since 1995, having cropped up during the now long-forgotten gif scare, when compuserve and unisys announced they would begin charging royalties for the use of the gif image format.
to provide gif support in their applications, software makers like adobe and macromedia must pay royalty fees – fees which are passed down to the end user in the selling cost of the software.
when png appeared on the scene, web designers were ready to make the switch to the free, superior format and shun gif forever. but over time, browsers continually failed to support png, and eventually most people started to forget about it. today, nearly everyone still uses gif habitually.
which is a shame, because png makes gif look pretty pathetic: it supports gamma correction, (sometimes) smaller file sizes, loss-less compression, up to 48-bit color, and, best of all, true alpha transparency.
to get why alpha transparency is a big deal, we must first understand one of the most annoying limitations of gif.
binary transparency: the scourge of gif
when it comes to transparency, gif doesn't cut it. whereas png supports alpha transparency, gif only supports binary transparency, which is a big limitation and has a couple of important implications.
for one, a gif image can either use no transparent colors at all or have one color that's completely transparent – there are no degrees of transparency.
and if a complex gif does contain a transparent color, the background color of the web page must match the transparent color, or else the anti-aliased area around the transparent color will be surrounded by ugly haloing and fringing. if you've spent more than five minutes as a web designer, you know what i'm talking about.
the result is that any anti-aliased transparent gif is inextricably tied to the background color of the web page on which it lives. if you ever decide to change that color, you must also change the gif.
miraculously, png doesn't behave that way. a png can be transparent in varying degrees – in other words, it can be of variable opacity. and a transparent png is background-independent: it can live on any background color or image. say you want your navigation on monkeys-run-amuck.com to be 65% opaque so you can see through it to your orangutan background image. you can do that. a transparent anti-aliased “gorillas, chimps, gibbons, et al” title that can sit on top of any background color or image? you can do that, too.
so what about browser support?
by now, of course, we'd all be up to our ears in pngs if browsers supported them reliably. but seven years after the format's inception, you still can't slap a png onto a web page like you can a gif or jpg. it's disgraceful, but not as bad as it sounds.
it turns out that most of the latest versions of the major browsers fully support alpha transparency with png – namely, netscape 6, opera 6, and recently-released mozilla 1, all on windows; and, for the mac, internet explorer 5, netscape 6, opera 5, mozilla 1, omniweb 3.1, and icab 1.9. incredibly, png even works on opera 6 for linux, on webtv, and on sega dreamcast.
now, what's missing from that list?
ie5.5+/win, bless its heart, will, in fact, display a png, but it doesn't natively support alpha transparency. in ie5.5+/win, the transparent area of your png will display at 100% opacity – that is, it won't be transparent at all.
bugger. so what do we do now?
proprietary code-o-rama: the alphaimageloader
filter
ie4+/win supports a variety of non-standard, largely ridiculous visual filters that you can apply to any image's style. you can, for instance, fade in an image with a gradient wipe, or make it stretch from nothing to full size, or even make it swipe into place circularly, like a scene change in star wars.
a non-pointless gem among these is the alphaimageloader
filter, which is supported in ie5.5+/win. when used to display a png, it allows for full alpha transparency support. all you have to do is this:
<div id="mydiv" style="position:relative; height:250px; width:250px; filter:progid:dximagetransform.microsoft.alphaimageloader» (src='myimage.png',sizingmethod='scale');"></div>
(line wraps are marked ». –ed.)
and you're in business. perfect alpha transparency. this code works great, with only the small drawback that it's not part of any accepted web standard, and no other browser on the planet understands it.
serving up pngs with javascript
so the trick is to determine the user's browser and serve up the images appropriately: if ie5.5+/win, then we use alphaimageloader
; if a browser with native png support, then we display pngs the normal way; if anything else, then we display alternate gifs, because we can't be sure that a png will display correctly or at all.
using a slightly tweaked version of chris nott's browser detect lite, we set some global variables to this effect that we can use later on.
// if ie5.5+ on win32, then display pngs with alphaimageloader if ((browser.isie55 || browser.isie6up) && browser.iswin32) { var pngalpha = true; // else, if the browser can display pngs normally, then do that } else if ((browser.isgecko) |» | (browser.isie5up && browser.ismac) |» | (browser.isopera && browser.iswin » && browser.versionmajor >= 6) |» | (browser.isopera && browser.isunix » && browser.versionmajor >= 6) |» | (browser.isopera && browser.ismac » && browser.versionmajor >= 5) |» | (browser.isomniweb && » browser.versionminor >= 3.1) |» | (browser.isicab && » browser.versionminor >= 1.9) |» | (browser.iswebtv) |» | (browser.isdreamcast)) { var pngnormal = true; }
(note for the faint of heart: complete source code for all the examples we cover is available at the end of the article.)
tactic 1: quick and dirty with document.writes
the simplest, most reliable way to spit out pngs is using inline document.writes based on the above detection. so we use a function like this:
function od_displayimage(strid, strpath, intwidth, » intheight, strclass, stralt) { if (pngalpha) { document.write('<div style="height:'+intheight+'px;» width:'+intwidth+'px;» filter:progid:dximagetransform.microsoft.alphaimageloader» (src=\''+strpath+'.png\', sizingmethod=\'scale\')" » id="'+strid+'" class="'+strclass+'"></div>'); } else if (pngnormal) { document.write('<img src="'+strpath+'.png" » width="'+intwidth+'"» height="'+intheight+'" name="'+strid+'" » border="0" class="'+strclass+'" alt="'+stralt+'" />'); } else { document.write('<img src="'+strpath+'.gif" » width="'+intwidth+'"» height="'+intheight+'" name="'+strid+'" » border="0" class="'+strclass+'" alt="'+stralt+'" />'); } }
now we can call the od_displayimage function from anywhere on the page. any javascript-capable browser will display an image, and, if we want to be really careful, we can accompany each call with a <noscript> tag that contains a regular <img>
reference. so the respectable browsers get pngs normally, ie5.5+/win gets them with the filter, and all other browsers get regular gifs, whether they have javascript turned on or not.
it's a time-tested method, but what if we want more control over our pngs?
tactic 2: the beauty & majesty of objects
when i told the programmer in the office next door that i was writing this article, he took one look at my code, glowered at me, and said, “fool. where's the abstraction? you need to use objects.”
so now we have a javascript object to display pngs. here's how we use it:
<html><head> <script language="javascript" src="browserdetect_lite.js" type="text/javascript"> </script> <script language="javascript" src="opacity.js" type="text/javascript"></script> <script type="text/javascript"> var objmyimg = null; function init() { objmyimg = new opacityobject('myimg','/images/myimage'); objmyimg.setbackground(); } </script> <style type="text/css"> #myimg { background: url('back.png') repeat; position:absolute; left: 10px; top: 10px; width: 200px; height: 200px; } </style> </head> <body onload="init()" background="back.jpg"> <div id="myimg"></div> </body> </html>
that's it. the cool thing about the opacityobject is that we just pass it a div id and an image path and we're done. using the appropriate technique, it applies the image as a background of the div, and from there we can do whatever we want with it. fill it with text, move it across the screen, resize it dynamically, whatever – just like any other div.
the object works in any css 1-capable browser that can dynamically apply a background image to a div with javascript. it's completely flexible, and we could even use it in place of the above function.
the trade-off is that it doesn't degrade as nicely. netscape 4.7/win/mac and opera 5/mac, for instance, won't display an image at all. and it has another significant problem, which is this:
ie5/mac only supports alpha transparency when the png resides in an <img>
tag, not when it's set as the background property of a div. so pngs displayed with the opacityobject will appear 100% opaque in ie5/mac. this problem is especially frustrating because ie5/mac is the only browser which natively supports png and behaves this way. we've notified microsoft about this apparent bug and hope for it to be fixed in an upcoming release.
but for now, these issues are the trade-off for flexibility. obviously, choose the right tactic based on the particular needs of your project. between them both, you can do pretty much anything with pngs – like, for instance...
example 1: translucent image on a photo
in this simple example, we see how the same 80% opaque png can be displayed on any kind of background: translucent image on a photo.
example 2: anti-aliased translucent navigation with rollovers
what a beautiful thing it would be, i'm sure you've thought from time to time, to create translucent anti-aliased images that work on any background. well, check it out: anti-aliased translucent navigation with rollovers.
mouse over the images, observe the behavior of the rollovers, and click “change background” to see how the images behave on different backgrounds. then view the source. there are a few things worth noting here:
- to preload the correct images, we create a variable called
strext
, which contains either “.png” or “.gif.” as long as our pngs and alternate gifs use the same names except for the file extension, the browser will only preload the images that it's actually going to use. - we create a class called
pnglink
and set the cursor property to “pointer.” we pass that class name to the function when we call it, and the function applies the class to the png. the result is that the user's pointer turns into a cursor when he rolls over the image links, even though, in ie5.5+/win, they're really just divs. (you might also want to add"display:block"
or"display:inline"
to your png class, depending on how you're using the images, to make them display correctly in netscape 6. (for details, see better living through xhtml.) - we also use a couple of rollover functions specifically for displaying pngs. it turns out that, while it's possible to dynamically swap out pngs using the
alphaimageloader
, ie5.5+/win has a tough time of it; it's damn slow, too slow for effective rollovers. what works better is to apply a background color to the div that contains the png – the color will shine through the transparent part of the image, and do it fast, too. when we call the function, we send along the name of the image to be displayed and an html color – ie5.5+/win will display the color, and the others will display the image. - notice how those images even have drop shadows. you could stick any background image or color behind them and they would still look great, even if the pngs were completely transparent. is that cool or what?
example 3: floating translucent div with html text inside
in the first two examples, we used the quick-and-dirty function from tactic one. now, we want our png to interact with other code on the page, so this time we display it with the opacityobject.
but remember – there are drawbacks to this approach (see above), the most heartbreaking of which is that this example doesn't work perfectly on ie5/mac. if that causes you pain, then there's always the quick and dirty function. otherwise, read on.
first we create a div, give it an id, and assign any style properties we want to it – height, width, font family, etc.
then we pass along the id of that div when we instantiate the opacityobject. we pass along the image path, too, and now we have a div with a translucent background. cool!
next we put some html text in the div and apply another unrelated object method to it (this object has nothing to do with the opacityobject – it could be any code you have lying around). now we can move the translucent div around the screen. wheee! floating translucent div with html text inside.
so there's a glimpse of what's possible with the opacityobject. you hardcore css/dom folks, go nuts.
variably opaque-r-you
download the source code for the object, functions, and examples we covered. all the code relies on our tweaked version of browser detect lite, which is included as well. variable opacity source code.
one png and one png only
this is all very exciting, but, as with many achievements that get web developers excited, making png work in today's browsers simply shouldn't be this hard. you might consider signing the to persuade microsoft to provide full png support in internet explorer. with any luck, this article will soon be obsolete.
in the meantime, post any ideas for improvements to this code in the discussion forum for this article. the png home site, for instance, talks about a few other obscure browsers that should support alpha transparency, but that haven't been verified yet. if you can verify any of these claims, or have any other valuable input, let us know, and we'll update the code accordingly.
resources
- png home site
-
alphaimageloader
filter page on msdn -
png behavior at webfx, an alternate way to make pngs display in ie. involves using the runtimestyle object. the downside with this approach is that it only correctly displays a png if it's displayed within an
<img>
tag, not if it's a css background image