PNG Alpha-Transparency
PNG transparency, unlike GIF transparency supports full alpha blending, so that the background blends into the transparent area depending on the value at which the alpha channel is set. Point being: there's no doubt why you may want to use PNGs in your website. As you may know, PNG transparency is supported by Internet Explorer 7 as well as Firefox, thus you have the most popular browsers covered already. However, Internet Explorer 6 does not support PNG transparency, so we need to find a workaround.
PNG Transparency with Internet Explorer 6
The workaround for IE6 involves using a short JavaScript code that uses a 1 pixel transparent GIF file to simulate the transparency for IE6. Here is the code for the JavaScript file:
if (navigator.platform == "Win32" && navigator.appName == "Microsoft Internet Explorer" && window.attachEvent && navigator.userAgent.indexOf("Opera")==-1)
{
document.writeln('<style type="text/css">img { visibility:hidden; } </style>');
window.attachEvent("onload", LoadPng);
}
function LoadPng()
{
var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
var itsAllGood = (rslt != null && Number(rslt[1]) >= 5.5);
for (var i = document.images.length - 1, img = null; (img = document.images[i]); i--)
{
if (itsAllGood && img.src.match(/\.png$/i) != null)
{
var src = img.src;
img.style.width = img.width + "px";
img.style.height = img.height + "px";
img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')"
img.src = "1px.gif";
}
img.style.visibility = "visible";
}
}
All you need to do is place this JavaScript in your page (or in a JS file and then in your page), as well as a 1 pixel GIF file named 1px.gif that is transparent. Believe or not, you're done. Here is a sample HTML file that benefits from this hack:
<html>
<head>
<title>Transparent JS</title>
<script type="text/javascript" src="TransparentPng.js"></script>
</head>
<body>
<div style="background-color: #666666; text-align: center;">
<img src="Transparent.png" alt="Transparent" />
</div>
</body>
</html>
You can file all this code in the ZIP file attached to this tutorial, as well as the 1 pixel transparent GIF file and a sample transparent PNG file.
Download PNGTransparency.zip
The Downside
There is something you should know: if you are going to have a lot of PNG files that use transparency in a single page, it's going to increasing the loadng time because Internet Explorer will have to process the JavaScript code and apply the transparency for all those files. You shouldn't see any serious increased loading time for 10 transparent PNG files or less. However try placing 100 and it becomes a real problem. So try not to overuse this workaround, at least until most IE6 users migrate to IE7 and you can afford to alienate the few remaining users. |