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

Is there a better way to darken a background image?

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

<div class="slide">
  <div class="slide-overlay">
    <div class="slide-content">
      <h1>Blah blah content</h1>
    </div>
   </div>
</div>

我是这样设计的

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

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

唯一可以简化的是省略 .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;
}
<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>

编辑: 伪元素下方的文本不再分别受叠加的 alpha 通道影响。

您还可以使用多个背景:

.slide {
    background-image: linear-gradient(rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.2)),                                            
                      url('/assets/img/bg-cover.jpg')
    background-size: cover
}