简体   繁体   中英

[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;
}

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.

Try like this: Demo

CSS:

section {
    height: 200px;
    width: 300px;
}
section p {
    color: white;
    position:relative;
}
section:before {
    content:url(http://www.freeimages.com/assets/182929/1829283516/blue-sunset-1446196-m.jpg);
    filter:alpha(opacity=50);
    filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0.5);
    opacity:.50;
    position: absolute;         
    z-index: -1;
}

Gave more opacity in this updated demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM