<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.
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.
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.
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).
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.
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.
The best way is setting transparent png to background..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With