Search code examples
htmlcssbackground-imageopacity

[HTML][CSS] How to change opacity of background-image but not the text on it?


I want to create a square with a background image and text on it and manipulate the background image's opacity.

The problem is when I am applying an opacity value, it also changes the text. I tried to put two sections inside the square, I also tried to change the opacity of the background image and then set the opacity of the text back to 1 but that doesn't work.

HTML:

<section>
  <p>TEST</p>
</section>

CSS:

section {
  height: 200px;
  width: 300px;
  background-image: url(Graphic/background.jpg);
  opacity: 0.5;
}

section p {
  color: white;
  opacity: 1;
}

Solution

  • Use following CSS will help to solve your issue:

    Give image url to section after or before. and give opacity with that. So, it will not effect to text.

    section {
    width: 200px;
      height: 200px;
      display: block;
      position: relative;}
    
    section:after{
        content: "";
      background: url(http://video-js.zencoder.com/oceans-clip.png);
      opacity: 0.5;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      position: absolute;
      z-index: -1;   
    }
    }
    
    section p {
        opacity: 1;}
    <body>
    
            <section>
                <p>TEST</p>
            </section>
    
    </body>

    Check Fiddle.