【问题标题】:How do I change the opacity of a background image without affecting child elements?如何在不影响子元素的情况下更改背景图像的不透明度?
【发布时间】:2017-03-17 10:49:59
【问题描述】:

我正在尝试将背景图像设置为 70% 的不透明度,而不影响其前面的文本(在同一个 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>

【问题讨论】:

标签: html css background opacity


【解决方案1】:

通过使用伪元素和position:absolute

请注意,作为home 的直接子元素的元素需要一个位置,就像我设置为content 一样,或者您需要在伪元素上设置z-index: -1,如果没有, 伪将在顶部分层

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>

【讨论】:

    猜你喜欢
    • 2011-06-27
    • 2014-05-16
    • 2016-02-25
    • 2019-05-03
    • 2014-11-23
    相关资源
    最近更新 更多