Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS opacity and child elements

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

like image 408
Rob Avatar asked Apr 01 '10 15:04

Rob


People also ask

How do you use opacity without affecting children's elements?

Answer: Use the CSS RGBA colors There is no CSS property like "background-opacity" that you can use only for changing the opacity or transparency of an element's background without affecting its child elements.

How do you override opacity in a child element?

Basically, you can't override the opacity of a child. The answer you might be looking for will depend on what it is you are actually trying to do. Paulie is right, opacity effects the entire element (including children) and can't be reversed by a child element.

Is opacity inherited CSS?

Opacity is not inherited, but because the parent has opacity that applies to everything within it. You cannot make a child element less transparent than the parent, without some trickery. Values are a number from 0 to 1 representing the opacity of the channel (the “alpha” channel).

How do I make opacity not affect my text?

The percentage of opacity is calculated as Opacity% = Opacity * 100 To set the opacity only to the background and not the text inside it. It can be set by using the RGBA color values instead of the opacity property because using the opacity property can make the text inside it fully transparent element.


2 Answers

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.

like image 51
fuxia Avatar answered Sep 28 '22 03:09

fuxia


The best way is setting transparent png to background..

like image 24
yasink Avatar answered Sep 28 '22 03:09

yasink