Cross-Browser Variable Opacity with PNG: A Real Solution

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?

Article Continues Below

Share This:

Job Board

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.

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:

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.

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:

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…

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 petition 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 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

170 Reader Comments

More from ALA

Columns

How sustainable is a model where social networks take a central role in our daily routine? Antoine Lefeuvre believes there’s growing awareness that social networking tools don’t necessarily bring out the best in us. While we do want and appreciate tools that let us engage with others and do things together, we’re getting tired of the high price in attention and stress.

We take it for granted that career progress means moving into a management role. Even people who thrive in the individual contributor role feel the pressure to join management. Shouldn’t both capacities be valued, so we can find where we genuinely fit in and do our best work? Rian van der Merwe has gone scouting up the career path and realized it’s okay to turn back and be the other, oft-overlooked but equally important half of the management/making dynamic.

February 19, 2015

From the Blog

This week, the ALA staff is thinking about color accessibility, the process of building a vocabulary, the current state of web typography, and the lessons we can learn from skater culture. In other words: it's all about inclusion.

A decade ago here in A List Apart, we published a radical article by Peter-Paul Koch arguing for custom attributes in markup. Today, Mat Marquis takes a look back at how times have changed, and shows how PPK’s idea has worked its way into the web.

New content projects present a classic chicken-and-egg problem: should we start with the words, or focus on the structure they’ll take? There are benefits and challenges either way, but Eileen Webb has recently become a believer that starting with structure creates a better workflow for developers, designers and content creators alike.

It’s a new kind of blog post: straight from our brains to your hearts, we’re sharing what we think is neat on the web. This week: thoughts on Flipboard, diversity in tech, and advice for organizing conferences.

Ready for something new? We're excited to announce ALA: On Air, community-focused events where our readers can get to know our authors, staff, and others who are shaking up our industry. Mat Marquis shares all the details, and has specifics on our first event, Designing for Performance, coming up on February 26.