Cross-browser transparent backgrounds

September 30th, 2011

I had some trouble getting transparent backgrounds to work in ‘all’ browsers, so here’s how I accomplished it.

Proper browsers support `rgba()` colours, which allows you to specify a value for the alpha channel, which is transparency. Internet Explorer doesn’t support that, so you have to use a filter.

I also wanted to fall back on a solid colour for browsers I hadn’t supported (although this method supports latest Chrome, Firefox and Safari, and IE 5.5-8).

One slight hiccup, was that the IE filters would apply on top of the background colour, so when I set the background to black, for browsers that didn’t recognise the rgba or IE filter, my boxes came out black in IE. When I removed the background attribute, a lower class CSS came through, which set the background to white, and the boxes went grey in IE. So, for IE’s filters to work, you have to set the background to `none`. This broke my fallback to black, so I had to apply the IE-only CSS hacks to an extra background, for IE’s benefit.

Here’s the CSS for making a <div> have a translucent black background.

/* Fallback for browsers that don't support alpha-colours */
background: black;

/* For IE 8. The colours are aarrggbb. */
background: none\9;
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";

/* For IE 5.5 - 7. The colours are aarrggbb. */
*background: none;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);

/* RGBa with 0.6 opacity */
background: rgba(0, 0, 0, 0.6);

Leave a Reply