Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set opacity of background image without affecting child elements

Tags:

css

opacity

Is it possible to set the opacity of a background image without affecting the opacity of child elements?

Example

All links in the footer need a custom bullet (background image) and the opacity of the custom bullet should be 50%.

HTML

<div id="footer">
    <ul>
        <li><a href="#">Link 1</a></li>
        <li><a href="#">Link 2</a></li>
        <li><a href="#">Link 3</a></li>
        <li><a href="#">Link 4</a></li>
        <li><a href="#">Link 5</a></li>
    </ul>
</div>  

CSS

#footer ul li {
    background: url(/images/arrow.png) no-repeat 0 50%;
}  

What I've Tried

I tried setting the opacity of the list items to 50%, but then the opacity of the link text is also 50% - and there doesn't seem to be a way to reset the opacity of child elements:

#footer ul li {
    background: url(/images/arrow.png) no-repeat 0 50%;
    /* will also set the opacity of the link text */        
    opacity: 0.5;
}

I also tried using rgba, but that doesn't have any effect on the background image:

#footer ul li {
    /* rgba doesn't apply to the background image */
    background: rgba(255, 255, 255, 0.5) url(/images/arrow.png) no-repeat 0 50%;
}
like image 945
jmohr Avatar asked Oct 14 '22 03:10

jmohr


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 I change the background opacity without affecting 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.

How do you make a background transparent without affecting text CSS?

One approach you can use is to put the background-image styles in a pseudo-element of the parent element. Since the pseudo-element is a sort of child of the parent, you can change the opacity of it without affecting the text content.

Can you set an opacity to a background image?

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.


1 Answers

You can use CSS linear-gradient() with rgba().

div {
  width: 300px;
  height: 200px;
  background: linear-gradient(rgba(255,255,255,.5), rgba(255,255,255,.5)), url("https://i.imgur.com/xnh5x47.jpg");
}
span {
  background: black;
  color: white;
}
<div><span>Hello world.</span></div>
like image 222
Stickers Avatar answered Oct 16 '22 15:10

Stickers