1

in the try it yourself page, http://www.w3schools.com/cssref/tryit.asp?filename=trycss3_opacity, they set the opacity of the div to be 60%. In doing so, the black text also changed. Is there a way to achieve the effect of having the div transparent without modify the opacity of the text?

Doboy
  • 10,411
  • 11
  • 40
  • 48
  • http://stackoverflow.com/questions/6624457/how-to-set-opacity-to-the-background-color-of-a-div/6624569#comment-7823841 Note that i do have comment there ( under Phil's answer ) showing a way to do it with css opacity, if that is the preferred way. – Joonas Aug 14 '11 at 14:09

2 Answers2

1

Yes, there is a way to do this. You can make use of rgba values

See this - http://jsfiddle.net/aniketpant/jR2ZZ/

Instead of using opacity, use rgba

HTML

<div>
This element's opacity is 0.5! Note that both the text and the background-color are affected by the opacity level!
</div>

CSS

div {
    background: rgba(255, 0, 0, 0.5);
}
Aniket
  • 9,622
  • 5
  • 40
  • 62
0

Yes and no. opacity itself will always affect the children of the element it's on, and there's nothing you can do about it.

What you can do is give the div a background-color using RGBa - for instance div { background-color: rgba(0,0,0,0.6); /* 60% opaque black */ } That will affect only the div it's applied to, but not children or content.

Support for RGBa isn't universal - Firefox and Chrome support it, but IE 8 and below don't, so remember to specify a fallback colour.

See here for more details.

Chowlett
  • 45,935
  • 20
  • 116
  • 150