Can I assign the opacity
property to the background
property of a div
only and not to the text on it?
I've tried:
background: #CCC; opacity: 0.6;
but this doesn't change the opacity.
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.
Simply use rgba to define your background color and specify opacity with it at the same time by adjusting the last value, for alpha, in your rgba code. For scaling, bringing the value closer to 0 increases transparency. To simplify your HTML, you don't even need the parent div around your block of text to do this.
Changing the opacity of the background color only To achieve this, use a color value which has an alpha channel—such as rgba. As with opacity , a value of 1 for the alpha channel value makes the color fully opaque. Therefore background-color: rgba(0,0,0,. 5); will set the background color to 50% opacity.
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).
It sounds like you want to use a transparent background, in which case you could try using the rgba()
function:
rgba(R, G, B, A)
R (red), G (green), and B (blue) can be either
<integer>
s or<percentage>
s, where the number 255 corresponds to 100%. A (alpha) can be a<number>
between 0 and 1, or a<percentage>
, where the number 1 corresponds to 100% (full opacity).RGBa example
background: rgba(51, 170, 51, .1) /* 10% opaque green */ background: rgba(51, 170, 51, .4) /* 40% opaque green */ background: rgba(51, 170, 51, .7) /* 70% opaque green */ background: rgba(51, 170, 51, 1) /* full opaque green */
A small example showing how rgba
can be used.
As of 2018, practically every browser supports the rgba
syntax.
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