mrseanbaines
mrseanbaines

Reputation: 833

How do I change the opacity of a background image without affecting child elements?

I am trying to make the background image at 70% opacity without affecting the text in front of it (within the same div).


HTML

#home {
  opacity: 0.7;
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  background-image: url("...");
  min-height: 100%;
  overflow: hidden;
}

div .welcome {
  background-size: cover;
  vertical-align: middle;
  text-align: center;
  font-family: 'Lobster', cursive;
  font-weight: 900;
  font-size: 60px;
  color: black;
  margin: auto;
}
<div id="home" class="section">
            <p class="welcome"><strong>Hello,<br>My name is Sean</strong></p>
          </div>

Upvotes: 1

Views: 791

Answers (1)

Asons
Asons

Reputation: 87201

By using a pseudo element and position:absolute

Do note that element that is a direct child of the home will need a position, like I set to the content, or you need to set z-index: -1 on the pseudo element, and if not, the pseudo will be layered on top

body {
  background: blue
}
#home {
  position: relative;
  min-height: 100%;
  overflow: hidden;
}

#home::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  opacity: 0.5;
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  background-image: url(http://placehold.it/200/f00);  /*  image is red but blue shine 
                                                           through so becomes purple */
}

.content {
  position: relative;
  color: white;
}
<div id="home">

  <div class="content">
    
    Content not affected
    
  </div>
  
</div>

Upvotes: 1

Related Questions