views:

865

answers:

3

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

+2  A: 

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.

easwee
+1  A: 

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.

David Thomas
Always declare a fallback without RGBa, like described in the article I linked to in my answer.
Marcel Korpel
@Marcel Korpel, yes, you're right (and edited with fallback).
David Thomas
@ricebowl: nope, this triggers a bug in IE 6/7: http://css-tricks.com/ie-background-rgb-bug/
Marcel Korpel
@Marcel Korpel, having read the page you linked to I'm not seeing the bug in IE6. Specifying a value it understands before specifying a value it doesn't seems to work for me (IE6 at work, on XP sp3)... =/
David Thomas
Oh, yeah. I used `background` not `background-color` in the test. My bad.
David Thomas
@ricebowl: :) And for the proprietary filter, also see http://css-tricks.com/rgba-browser-support/ (under "A better fallback for IE").
Marcel Korpel
+1  A: 

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).

Marcel Korpel