是否有更好的方法来使背景图像变暗?

Cli*_*een 4 html opacity css3

我有以下代码,以使背景图像变暗.一个带有背景图像的div然后是一个div,里面用透明度填充背景颜色

<div class="slide">
  <div class="slide-overlay">
    <div class="slide-content">
      <h1>Blah blah content</h1>
    </div>
   </div>
</div>
Run Code Online (Sandbox Code Playgroud)

而且我这样造型

.slide
    background-image: url('/assets/img/bg-cover.jpg')
    background-size: cover
.slide-overlay
    background-color: rgba(0, 0, 0, .2)
Run Code Online (Sandbox Code Playgroud)

有谁知道更优雅的解决方案?

F. *_*ler 6

您可以简化的唯一方法是省略.slide-overlay容器并添加伪元素(:before, :after).

这将是解决方案:

.slide {
    background-color: tomato;
    background-size: cover;
}
.slide-content {
    position: relative;
    color: white;
}
.slide-content:nth-child(2):before, .slide-content:nth-child(3):before {
    content: "";
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.2);
}
.slide-content:nth-child(3) {
    z-index: 1;
}
.slide-content:nth-child(3):before {
    z-index: -1;
}
Run Code Online (Sandbox Code Playgroud)
<div class="slide">
    <div class="slide-content">
         <h1>No effects - just standard text.</h1>
    </div>
    <div class="slide-content">
         <h1>With overlay - text is below the overlay.</h1>
    </div>
    <div class="slide-content">
         <h1>With overlay - text is above the overlay.</h1>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

编辑:伪元素下面的文字不再受叠加分别alpha通道的影响.