Madmix
Madmix

Reputation: 23

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

Upvotes: 2

Views: 848

Answers (2)

ketan
ketan

Reputation: 19341

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.

Upvotes: 3

G.L.P
G.L.P

Reputation: 7207

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

Upvotes: 1

Related Questions