Z-Index & Opacity

z-index specifies the location of an HTML element on a notional z-axis orthogonal to the display surface. The positive z-axis runs out of the display surface, towards the user. As discussed here, HTML element boxes are placed according to their z-index specification into an ordered list - a stacking context for the HTML page on display. Boxes higher up in the stacking context, i.e. more positive z-index, will be displayed later and will cause boxes lying underneath them to be wholly or partially obscured. This rule applies to all box types including absolutely positioned ones but not not to their children since absolutely positioned boxes own their own stacking context.

There are occasions when it is necessary to use a certain box stacking order but nevertheless cause a box lower down the stacking order to show through. This is accomplished by assigning a value for the opacity of the element. The standards compliant syntax for opacity is opacity: n where n is a number in the range 0..1. An element with an opacity setting of zero will be completely transparent. On the other hand, complete opacity is assured by omitting the opacity setting thereby causing it take its default value of 1.

IE uses its own syntax for defining opacity: filter:alpha(opacity= nn ) where nn lies in the range 0..100. However, this on its own works only if the element in question is positioned. The easiest way to get an element with default positioning to understand the filter:alpha setting is to also define the, currently IE specific, zoom attribute. For instance, filter:alpha(opacity=50);zoom=1.

Opacity and z-index specifications can be used together very effectively to create complex web pages with multiple layers and interesting hue/transparency effects - an interesting "washed out watercolor" effect for creating page backgrounds is available here. When designing such pages it is good practice to spread out the z-index values. Thus it is better to use z-indices of 10, 20, 30... rather than consecutive values of 1, 2, 3... . This makes it easier to modify the web page at a later date and put in extra layers.

<html>
<head>
<style>
.one{z-index:10;background-color:yellow;border:0.05em solid black;
left:1em;top:1em;height:4em;width:4em}
.two{z-index:20;background-color:green;border:0.05em solid black;
left:2em;top:-3em;height:5em;width:5em; opacity:0.5;filter:alpha(opacity=50)}
</style>
</head>
<body>
<div class="one"></div>
<div class="two"></div>
</body>
<html>

A final note on the subject of opacity - IE6 ignores opacity settings assigned to the select form control. This is only one of the myriad bugs that plague this browser. It is an especially unfortunate one since controlling opacity offers a neat way of styling selects to prevent websites from having a dated 1990s look to them.

Jump To...

Colophon