Pages

Saturday 30 January 2010

PNGs and IE6 without using JavaScript

To get IE6 to render PNGs without that white background you can use a combination of the IE propriatary CSS filter and Conditional Comments. There are lots of solutions out there that rely on Javascript to do this, but it really isn't neccessary.


For backgrounds

html:
<!--[if IE 6] >
    <link href="/content/css/ie6.css" media="screen" rel="stylesheet" type="text/css"<>/link>
    <![endif]-->
Stylesheet

background: none;
filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/content/images/emptynavback.png',sizingMethod='scale');

Explanation

The conditional comment means this style sheet will only be included for IE6. As filter is a proprietary IE CSS property and we only need it for IE6, this method ensures that IE7+ will not use the filter and your CSS will still return as valid for all other broswers.

Setting background:none removes the pesky PNG for IE6.

sizingMethod - There are 3 options available here; Image, Scale and Crop.

Scale - this will scale the image to the size of the container, use it when your image is a repeater.
Crop - this will crop the image to the size of the container.
Image - this will increase the size of the container to the size of the image.

Important note: Adding the filter property means the image is no longer a background image. You'll find that if you place any links inside the container that has the AlphaImageLoader, although you can see the links, you can't click on them!

Fortunately, there is a relatively simple fix for this. You can either add another container around the links and set position:relative; or you can apply position:relative; to the a tag itself.

Tip: Note the leading / in the src attribute. When your style sheet resides in a different directory to the images, if you try to set the src using a relative path it won't find the image. Use an absolute path instead, the will save you a lot of cursing!

For Images

Obviously, the above method won't work if the PNG is an image on your page. Though you can use a similar method. Wrap your image in a conatiner (<p>will do nicely). Give your image a class, say .hideImage:

.hideImage{display:none;visibility:hidden;}
 
Set the styling for your container to be fixed width and height, the same as the image (don't forget to display:block; if you are using <p>) and apply the filter to the container.

A nice solution to the problem of PNGs that will work with JavaScript off.

No comments:

Post a Comment