Override opaque text in a transparent div with CSS

mager picture mager · Mar 3, 2010 · Viewed 11.7k times · Source

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

Answer

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.