PNG transparency in Internet Explorer

From CodeCodex

One big annoyance to web developers is the lack of PNG transparency support in Internet Explorer. For reasons unknown Microsoft has made it unnecessarily complex to add PNG images to your web page that have transparency attributes.

Many people resort to using Javascript to overcome this, however, not everyone has JavaScript enabled, and some use browsers without Javascript at all! CSS can be used instead, by applying IE-specific filters to an image:

_background-image: none;

Note that the filter we use to do this is not recognized by any browser other than IE, and will not validate. So we need to differentiate between people using IE and people using other browsers, then display the image accordingly.



© Part or all of this code is protected under the GNU Free Documentation License.

PHP is used to sniff the user's browser and display the XHTML accordingly: plain tags for other browsers, and CSS filters for MSIE.

//parameters: url of image, image width, image height
function png_alpha($imgurl, $width=100, $height=100) {
   //check if user has IE browser
   if((stripos('msie', $_SERVER['HTTP_USER_AGENT']) !== false
     || stripos('microsoft internet explorer', $_SERVER['HTTP_USER_AGNET']) !== false) 
     && stripos('opera', $_SERVER['HTTP_USER_AGENT']) === false) {
      $is_msie = true; //using MSIE
   else {
      $is_msie = false; //other browser probably supporting transparency
   //if they are using IE
   if($is_msie) {
      return '<div id="png_image" 
   } else { //they are not using IE
      return '<img src="'.$imgurl.'" width="'.$width.'" height="'.$height.'">';

echo png_alpha('', 159, 140)


© Part or all of this code is protected under the GNU Free Documentation License.

If your webhost doesn't support PHP, or if you think PHP browser detection is unreliable, or if PHP adds processing overhead to your webpages, you can use inlined XHTML to create the same effect. The styles will not validate and may break in some browsers, but you can hide them using MSIE-specific conditional tags:

<!--[If IE]>
# MSIE-specific code...

To directly inline the filter:

<!--[if IE]>
<style type="text/css">
_background-image: none;

You can also create a specific CSS file. This may use up less bandwidth, because not evryone is going to download the CSS file; only those who use Internet Explorer.

<!--[if IE]>
<link rel="stylesheet" type="text/css" href="iefix.css" />
<!-- Of course, if you are using HTML and not XHTML, remove the trailing slash from behind the link tag. -->