如何在不影响子元素的情况下改变背景图像的不透明度?

时间:2021-09-03 20:33:47

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

我试图使背景图像不透明度达到70%而不影响前面的文本(在同一个div中)。


HTML

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>

1 个解决方案

#1


1  

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

请注意,home的直接子元素需要一个位置,就像我设置的内容一样,或者需要在pseudo元素上设置z-index: -1,如果不是,则pseudo将在上面分层

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>

#1


1  

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

请注意,home的直接子元素需要一个位置,就像我设置的内容一样,或者需要在pseudo元素上设置z-index: -1,如果不是,则pseudo将在上面分层

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>