Search code examples
internet-explorerpnginternet-explorer-6transparency

IE6 PNG transparency


How can I fix PNG transparency bug in IE6 for background image?


Solution

  • I like this Javascript solution writen by David Cilley some time ago. It gets out of the way of compliant browsers and can be used with any back-end you want. It does still require a blank gif image though.

    Add these functions to your HTML Header or other existing .js include:

    <script type="text/javascript">
        function fixPngs(){
        // Loops through all img tags   
            for (i = 0; i < document.images.length; i++){
                var s = document.images[i].src;
                if (s.indexOf('.png') > 0)  // Checks for the .png extension
                    fixPng(s, document.images[i]);
            }
        }
    
        function fixPng(u, o){
            // u = url of the image
            // o = image object 
            o.src = 'images/spacer.gif';  // Need to give it an image so we don't get the red x
            o.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + u + "', sizingMethod='scale')";
        }   
    </script>
    

    Put the following conditional comment at the bottom (footer section, just before </body> ):

    <!--[if lte IE 6]>
        <script language="javascript" type="text/javascript">
            //this is a conditional comment that only IE understands. If a user using IE 6 or lower 
             //views this page, the following code will run. Otherwise, it will appear commented out.
            //it goes after the body tag so it can fire after the page loads.
            fixPngs();
        </script> 
    <![endif]-->
    

    For a more comprehensive approach to IE6 oddities, try the IE7 Javascript library.