I am trying to make text inside a transparent div have no opacity, aka be completely black:
<div style="opacity:0.6;background:#3cc;">
<p style="background:#000;opacity:1">This text should be all black</p>
</div>
Is this possible to do with only CSS?
Thanks in advance
The easiest way is to style the background of the parent div with opacity/alpha:
div {
background: #fff; /* for browsers that don't understand the following rgba rule */
background-color: rgba(255,255,255,0.5); /* rgb, white, with alpha at 0.5 */
}
This is not, however, compatible with IE.
For IE >= 7 compatibility, you could use:
div {
background-image: url('path/to/partially_transparent.png');
background-position: 0 0;
background-repeat: repeat;
}
I recall that IE < 7 has a proprietary filter option, but I'm afraid I can't recall how it works. So I've omitted any attempt to describe/show it. If I can find a useful reference though I'll add it in later.
As noted by easwee the opacity is inherited by contained elements, which is why you can't override it, and is why I prefer to use the background-color
/background-image
approach.
The child elements inherit the opacity. What you could do is to position the <p>
outside the opaque div and set a negative margin to move it over it.
I came across this problem often and usually solved it like this. Problem is only when you have dynamic content and the div has to expand.
Does the background consist of a solid colour? If so, you could also use RGBa to select a transparent background colour for the div
that isn't inherited by its the children. Read RGBa Browser Support for more information, a workaround for IE and another solution.
If the background of the div
isn't solid, you can use a transparent PNG as background. Remember to use AlphaImageLoader in IE6 (and 5.5).