search

Home  >  Q&A  >  body text

Change background image opacity while preserving visibility of child elements

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

Example

All links in the footer require custom bullets (background image), and the custom bullets should have an opacity of 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 tried

I tried setting the list item's opacity to 50%, but the link text's opacity is also 50% - and there doesn't seem to be a way to reset the opacity of the 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 didn'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%;
}


P粉354602955P粉354602955442 days ago686

reply all(1)I'll reply

  • P粉574268989

    P粉5742689892023-10-11 13:07:40

    You can combine 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>

    reply
    0
  • Cancelreply