Picnic Website Code Tutorials

CSS Opacity Made Simple Tutorial

View Demo

Update: See Cross Browser Modern CSS Opacity With RGBA >>

I'll make this quick! A couple others have already documented this here and here. I took the best of both, updated the opacity filters, cleaned up the code, made it pretty, and most importantly, made it easy (or easier at least) to understand.

Bottom line: if you make a box transparent, all of it's children (e.g. the text) will also become transparent. Usually, this is not the desired outcome. Luckily, it's relatively simple to fix! IE only needs position relative applied to the inner elements like the p, h1, etc (or another div) to alleviate the problem. This time, it's the others (FX/Safari/Opera/Chrome) that make things more complicated. They also need position relative applied to the inner elements, but in addition to, they also need an extra container added (i.e. #apdiv) which holds the filters. Here is the code below, shone in it's most stripped down and basic form.

Note: IE needs "haslayout" on the element in question in order for it's opacity filters to work. And supposedly, the IE opacity filters must be used in the order that I have shone below. If you don’t use this order, IE8-as-IE7 won’t apply the opacity, although IE8 and a pure IE7 will. Also, -moz-opacity:.5; and -khtml-opacity:.5; are not needed anymore unless you care about much older versions of Mozilla and Safari.

The html

<div id="box"> 
<div id="apdiv"></div>


#box {
#box p {
#apdiv {
opacity:.5; /* FX/Opera/Safari/Chrome */
-ms-filter:"alpha(opacity=50)"; /* IE8 */
filter:alpha(opacity=50); /* IE6/IE7 */

...And for IE6. IE6 does not understand three values for an absolute positioned element (i.e. top:0;left:0;bottom:0;). So, an easy way to fix that, is to feed it this expression shone below. Alternatively, instead of using an expression, you can feed IE6 a large height on the #apdiv (e.g. #apdiv{height:999em;}) and just hide the overflow. However, I like the expression - it's a hell of a lot cleaner!

* html #apdiv{height:expression(this.parentNode.offsetHeight);}

Need help adding this or other code to your website? Post it here in the forum! Forum


Top Donators

Friends of Mine