Layers Part 2 Setting Layer Opacity

Published on 2001-08-04 by John Collins. Please follow me on Twitter for more: 

In the example code below, both the "pink" and red example are in fact the same red colour. The green layer lies behind both red layers and has a lower z-index, while being visible through the red layers because their opacity (or level of transparency) is set below 100%.

The pink layer is set to 25% opacity, the red to 75%, while the green layer is set to the default 100% opacity setting. Here is the code for the layers:

<html>
<head>
 
<style type="text/css">
#pink {position:absolute; left:100px; top:150px; width:100px; height:100px; 
background-color:red; z-index:2; filter:alpha(opacity=25); -moz-opacity:0.25;}
#red {position:absolute; left:250px; top:150px; width:100px; height:100px; 
background-color:red; z-index:2; filter:alpha(opacity=75); -moz-opacity:0.75;}
#green {position:absolute; left:175px; top:195px; width:100px; height:100px; 
background-color:green; z-index:1; filter:alpha(opacity=100); -moz-opacity:1.0;}
</style>
 
</head>
<body>
 
<div id="pink"></div>
<div id="red"></div>
<div id="green"></div>
 
</body>
</html>

Syntax:

Internet Explorer 5+: filter:alpha(opacity=100);

To adjust the level of opacity in IE5 you simply change the value from 100 (opaque) to anything below that, 0 being completely transparent.

Netscape 6: -moz-opacity:1.0;

As with IE5+, NS6+ only requires you to change the 100% setting to something lower than that. Netscape is new to supporting opacity, and to be honest I have found this technique to be slightly 'buggy'. Support for this technique is greatly improved with NS6.1, so I would recommend this version. If you have any problems let me know.


Updated 2020 : note that the above examples are now out-of-date, given this post was originally published in 2001. Now, you can simply use the opacity setting in CSS to get the same results, regardless of browser, e.g. to get 50% opacity use the following CSS:

opacity: 0.5;