CSS opacity and child elements
Asked Answered
G

3

18
<style type="text/css">
div#foo {
    background: #0000ff;
    width: 200px;
    height: 200px;

    opacity: 0.30;
    filter: alpha(opacity = 30);
}
div#foo>div {
    color: black;
    opacity:1;
    filter: alpha(opacity = 100);
}
</style>

<div id="foo">
    <div>Lorem</div>
    <div>ipsum</div>
    <div>dolor</div>
</div>

In the above example, the opacity of div#foo is inherited by child elements, causing the text to become nearly unreadable. I suppose it's wrong to say it is inherited, the opacity is applied to the parent div and the children are part of that, so attempting to override it for the child elements doesn't work because technically they are opaque.

I typically just use an alpha png background image in such cases, but today i'm wondering if there's a better way to make a background of a div semi-transparent without affecting the contents.

Garlan answered 1/4, 2010 at 15:19 Comment(0)
C
40

You may use rgba().

div#foo
{
    background: rgba(0, 0, 255, 0.3);
}

To make it work in old Internet Explorers use CSS PIE. There are some limitations, but those are handled in a backwards compatible way: the RGB value will be rendered correctly and the opacity will be ignored.

Creigh answered 1/4, 2010 at 15:23 Comment(4)
I wrote about using it in a backwards compatible fashion a while ago: dorward.me.uk/www/css/alpha-colourExhibitioner
Thanks, I learned something! Unfortunately it doesn't seem to work in IE7.Garlan
Its a CSS 3 feature. IE8 was the first version of IE advertised as having a complete CSS 2.1 implementation. I wouldn't expect many CSS 3 features until version 9.Exhibitioner
WOW! I can't believe how easy PIE is. How have I not heard of this before? I have only tested a few things on it so far, but everything seems to work beautifully, and it was SUPER easy :) Good job, IE! With this and conditional comments, I believe I can stop bad-mouthing Internet Explorer :)Eadmund
B
7

The best way is setting transparent png to background..

Bactericide answered 15/12, 2010 at 14:10 Comment(0)
T
5

If you use opacity, you'd have to put them in separate DIV's and then line them up together. The background DIV would have the lower opacity, and foreground DIV would have your content with 100% opacity.

Tyrosine answered 1/4, 2010 at 15:34 Comment(1)
RGBA color is nice, but if you need to support IE8, then use this approach. Just add an absolutely positioned DIV as the first child to the DIV in question with the needed opacity setting (and background image if alpha blending is required)Ectoenzyme

© 2022 - 2024 — McMap. All rights reserved.