【问题标题】:Is there a better way to darken a background image?有没有更好的方法来使背景图像变暗?
【发布时间】:2015-10-10 03:55:28
【问题描述】:

我有以下代码来使背景图像变暗。一个带有背景图像的 div,然后是一个 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)

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

【问题讨论】:

  • 你的代码在我看来不错
  • 我也是,我会这样做的。
  • 谢谢大家,我会坚持我所拥有的。干杯

标签: html css opacity


【解决方案1】:

您还可以使用多个背景:

.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
}

【讨论】:

    【解决方案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通道的影响。

    【讨论】:

    • 谢谢伙计,我可能会坚持我目前的做法,但这是一个不错的选择。干杯
    • 看起来不错。但是这样做的问题是你的h1也变暗了。
    • @MiguelGarrido 我刚刚解决了这个问题。没什么大不了。但感谢您的意见。 :)
    • 看起来好多了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2015-06-29
    • 2020-04-19
    • 2017-03-07
    • 2019-06-11
    • 2017-11-10
    • 1970-01-01
    • 2014-02-21
    • 2020-06-02
    相关资源
    最近更新 更多