Avoiding inheritance of opacity in CSS?

Well, it’s gonna be tough I guess.

I know opacity is always inherited by definition, but is there an easy way (easier than making 3 divs - container, one with defined transparency and third one with content) to avoid inheritance of opacity?

Easy example:

<span><p>I'm a text!</p></span>
span {
background-color: red;
opacity: .4;
width: 200px;
height: 50px;

p {
opacity: 1;

The child ALWAYS inherits opacity from it’s parent.

If you know the solution - please share.

Of course you’re not allowed to edit the html line, because structure hacks are easy :wink:


Yeah, you can’t avoid that, so one messy way around it is to absolutely position one element over another.

In my view, though, it’s better to use semi-transparent images and/or rgba colors (though the latter won’t work in some browsers).

Anyway, here are some opacity workaround links:


In the specific case above, the best option would be to absolute position the P inline with the opacity background thereby overriding inheritance.

Absolute positioning doesn’t have to be messy, I’ve used it plenty of times - you just need to know what you’re doing. :stuck_out_tongue:

Even with the finesse of a CSS artist, I still think of it as messy.

There are a few bits of reading that might answer your question.

According to Sitepoint forum thread, there’s nothing you can do - the opacity is applied to the parent element after child elements have been drawn, which is why child elements will look washed out but won’t actually be semi-transparent.

Impressive Webs has a hacky way to achieve the effect you’re after, although doesn’t recommend using it.

Edit: Oops, just spotted that Ralph has already given that one…

Steven York seems to have a better solution. Essentially, any solution is likely to involve having a faux-child element that is positioned so it looks like a child element, but is actually outside the parent element.

(Oh, and about not messing with the HTML? If you give me a <p> inside a <span>, I’m not going to leave that untouched! That is seriously not allowed, and is likely to cause untold problems for you)

It’s not all that difficult to just use two divs, one over the other - as others have suggested. This keeps the mess confined! Here is a page that does just that.


<title>Opacity Test</title>
<style type=“text/css”>
body { background-color:#FFF; font-weight:normal; color:#000; }
#redDiv { opacity: 0.2; position:absolute; top:100px; left:100px; width:200px; height:50px; background-color: #F00; }
#txtDiv { opacity: 1; position:absolute; top:115px; left:120px; text-align:left; background-color: }
.a13B { font-weight:bold; }


<div id=“redDiv”>
<!-- end redDiv –>
<div id=“txtDiv” class=“a13B”>
I’m a text!</div>
<!-- end txtDiv –>



That’s easy enough when you don’t need them to overlap. The problem comes when you need a totally opaque element inside a larger semi-transparent element.