I am trying to make text inside a transparent div have no opacity, aka be completely black:
<div style="opacity:0.6;background:#3cc;">
<p style="background:#000;opacity:1">This text should be all black</p>
</div>
Is this possible to do with only CSS?
Thanks in advance
To set the opacity of a background, image, text, or other element, you can use the CSS opacity property. Values for this property range from 0 to 1. If you set the property to 0, the styled element will be completely transparent (ie. invisible).
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.
Transparency using RGBA In addition to RGB, you can use an RGB color value with an alpha channel (RGBA) - which specifies the opacity for a color. An RGBA color value is specified with: rgba(red, green, blue, alpha). The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).
There is no background-opacity property in CSS, but you can fake it by inserting a pseudo element with regular opacity the exact size of the element behind it.
The easiest way is to style the background of the parent div with opacity/alpha:
div {
background: #fff; /* for browsers that don't understand the following rgba rule */
background-color: rgba(255,255,255,0.5); /* rgb, white, with alpha at 0.5 */
}
This is not, however, compatible with IE.
For IE >= 7 compatibility, you could use:
div {
background-image: url('path/to/partially_transparent.png');
background-position: 0 0;
background-repeat: repeat;
}
I recall that IE < 7 has a proprietary filter option, but I'm afraid I can't recall how it works. So I've omitted any attempt to describe/show it. If I can find a useful reference though I'll add it in later.
As noted by easwee the opacity is inherited by contained elements, which is why you can't override it, and is why I prefer to use the background-color
/background-image
approach.
The child elements inherit the opacity. What you could do is to position the <p>
outside the opaque div and set a negative margin to move it over it.
I came across this problem often and usually solved it like this. Problem is only when you have dynamic content and the div has to expand.
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