Cross-Browser Background Opacity with CSS3

Along with all kinds of other nifty things in CSS3 is the ability to set background colors to semi-transparent. Before CSS3, this could be achieved using a semi-transparent .png, if the browser supported .png’s, or by using some other graphic method.

CSS3 lets you use an rgba (red blue green alpha) color definition.

The rgb color designation has always been available, where the color is defined as red, green, blue values: rgb(255,255,255) for example. With the addition of an alpha value, the color can be semi-transparent: rgba(255,255,255,.7), with .7 being 70% opaque. This works great in all browsers except Internet Explorer less than version 8. Because v7 & 8 will be around for a while yet, this CSS3 rule can be used with a hack for IE.

IE can handle gradients using a filter, and if the filter is set to start and end with the same color and opacity, that would be semi-transparent. Here’s an example:

.your-element-class {
/* fallback for really old browsers - solid color */
background-color: rgb(200,200,200);
/* for most browsers */
background-color: rgba(200,200,200,0.8);
/* for ie less than v8 */
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#ccdddddd,↵
endColorstr=#ccdddddd);
/* for ie v8 */
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ccdddddd,↵
endColorstr=#ccdddddd)";
}

In the rgba designation, the three colors come first as rgb values with opacity last (0.0 = transparent, 1.0 = opaque). In the IE filters, the opacity is first, with the colors following all designated in hex.

In this example, 200 in rgb is represented by dd in hex, and 0.8 opacity is represented by cc in hex.

With these tools, CSS3 semi-transparent backgrounds are available for all browsers.

Here’s a link to a Hex to RGB converter

View Comments

Leave a Reply