Forum Moderators: not2easy
5.1. opacity
Opacity [w3.org] is the ability to cover whats underneath. It's the opposite to transparency.
Syntax: opacity: X
There is a complexity in this: the browsers are supposed to generate the image of an element and all it's descenders off screen and then put it on-screen, which makes it impossible for the different layers of the element to be interlaced with other elements. And therefore opacity has this rather complex instruction for browser makers:
implementations must create a new stacking context for any element with opacity less than 1. If an element with opacity less than 1 is not positioned, implementations must paint the layer it creates, within its parent stacking context, at the same stacking order that would be used if it were a positioned element with ‘z-index: 0’ and ‘opacity: 1’. If an element with opacity less than 1 is positioned, the ‘z-index’ property applies as described in CSS21, except that ‘auto’ is treated as ‘0’ since a new stacking context is always created.
The gist is that setting opacity to less than 1 forces the browser to create a new stacking context. And that new stacking context changes how z-index works just like giving something "position" changes such things.
Example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>test</title>
<style type="text/css">
* {
padding: 0;
margin: 0;
}
html {
height: 100%;
background-color: white;
padding: 2em;
}
body {
background-color: black;
color: white;
opacity: 0.5;
padding: 2em;
}
h4, p {
background-color: red;
}
h4 {
opacity: 0.5;
}
</style>
</head>
<body>
<h4>hello world</h4>
<p>hello world</p>
</body>
</html>
Notice there isn't a way to use the opacity property and have a child excluded from the opacity.
Support:
Graceful fallback:
For older mozilla based browsers the -moz-opacity property does the same thing as opacity does in Firefox 3.5 .
For older webkit based browsers (Opera and Chrome), the -webkit-opacity property does the same thing as opacity does in Safari 4.0 .
For IE there are proprietary filters that one could use to achieve the same effect from a conditional comment.
IE8:
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=XX)"; filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=XX); Practical use
Opacity on elements (and all their children) has a limited use mostly limited to images, setting translucent colors (front and/or background is far more attractive for many real cases ...