Search code examples
htmlcssopacity

Apply opacity to background image but not text


My problem is when I make my picture darker the text in class .text gets darker too, and I don't know how to avoid this.

I know one solution: to make .wrap position:absolute and class .text make not in image but this solution is unsuitable for me (like this).

Any other ideas?

This is the code that I have:

.wrap {
  width: 100%;
  background: #000 none repeat scroll 0% 0%;
}
.image {
  background-image: url("https://pbs.twimg.com/profile_banners/1550273796/1372363601/1500x500");
  background-size: cover;
  opacity: 0.8;
  height: 100vh;
  max-height: 350px;
  min-height: 200px;
}
.text {
  color: #FFF;
  font-weight: 900;
}
<div class="wrap">
  <div class="image">
    <div class="text">
      <p>I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE
        YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU</p>
    </div>
  </div>
</div>

jsfiddle demo


Solution

  • opacity is not an inherit property but affect the content so when you increase the opacity of .image that also affects to .text, you can use pseudo elements and background: rgba() to achieve what you want like this:

    Here a working JSFiddle to play with

    .wrap {
        width: 100%;
    }
    .image {
        background-image: url("https://i.sstatic.net/gijdH.jpg?s=328&g=1");
        position: relative;
        height: 100vh;
    }
    .image:before{
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        left: 0;
        bottom: 0;
        background: rgba(0,0,0,0.7);
    }
    .text {
        color: #FFF;
        position: relative;
    }
    <div class="wrap">
        <div class="image">
            <div class="text">
                <p>I LOVE YOU</p>
            </div>
        </div>
    </div>