Search code examples
htmlcssopacity

CSS : Background opacity is showing on text


Take this Code for example

#backgroundimage {
  background: url("https://www.solidbackgrounds.com/images/640x480/640x480-aero-solid-color-background.jpg");
  height: 50px
}

#container {
  background-color: #4C4C4C;
  opacity: 0.5;
}

#text {
  color: #ffffff;
  opacity: 1;
}
<div id="backgroundimage">
  <div id="container">
    <p id="text">
      Some text here
    </p>
  </div>
</div>

I want to make the text color white while keeping the background image and container opacity intact. Look at this image as Reference


Solution

  • Have a look at the following example. Instead of opacity use rgba. According to docs:

    opacity applies to the element as a whole, including its contents, even though the value is not inherited by child elements. Thus, the element and its children all have the same opacity relative to the element's background, even if they have different opacities relative to one another.

    #backgroundimage {
      background: url("https://www.solidbackgrounds.com/images/640x480/640x480-aero-solid-color-background.jpg");
      height: 500px
    }
    
    #container {
      background-color: rgba(76,76,76,.5);
    }
    
    #text {
      color: #ffffff;
    }
    <div id="backgroundimage">
      <div id="container">
        <p id="text">
          Some text here
        </p>
      </div>
    </div>