Thursday, June 11, 2009

Controlling Opacity of a background color using CSS

If you want want to have a background color be semi-transparent (a color with opacity of less than 100%), Cascading Style Sheets (CSS) may be what you have been looking for.

FireFox and Internet Explorer implement the feature differently. However, both implements can co-exist in one CSS class so there is no need for fancy code to swap between the two depending on the browser.

.mySemitransparentBackground {
background-color: Gray;
filter:progid:DXImageTransform.Microsoft.alpha(opacity=70);
opacity: 0.7;
}

In this example, the background color is Gray, but could be any color. The line that starts filter is for Internet Explorer, and the line that starts with opacity is for FireFox. Notice that Internet Explorer takes the value 70 to specify that the color is 70% opaque, and FireFox use the decimal version which is 0.7 to specify the same 70% opacity. Note, that 100% means that your color will be solid / not transparent (no background will be seen through it). Be sure both values represent the same value, otherwise you will get different opacity for each browser.

NOTE: I have verified that the FireFox stuff also works for Safari on Windows. If anyone else confirms any other browsers or platforms, please let me know. Thx!

2 comments:

Term Papers said...

I have been visiting various blogs for my term papers writing research. I have found your blog to be quite useful. Keep updating your blog with valuable information... Regards

Shawn Gilhespy said...

I understand how to control the opacity of my posts background, but in doing so, the code also likes to do the same to my text and images.

Is there a way I can keep JUST the background at a certain opacity without changing the contents of the posts opacity?