Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override opaque text in a transparent div with CSS

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

like image 772
mager Avatar asked Mar 03 '10 17:03

mager


People also ask

How do you change the opacity of text in CSS?

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

How do I change the opacity of text without affecting CSS?

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.

How do you control opacity in CSS?

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

How do you change transparency opacity in CSS?

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.


2 Answers

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.

like image 94
David Thomas Avatar answered Sep 30 '22 19:09

David Thomas


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.

like image 35
easwee Avatar answered Sep 30 '22 18:09

easwee