2015-07-20 95 views
4

我有以下代码为了使背景图像变暗。与背景图像的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) 

有谁知道一个更优雅的解决方案的背景色填充呢?

+0

你的代码看起来不错,我 –

+0

我也一样,这是我会怎么做。 –

+0

谢谢你们,我会坚持我的话。干杯 –

回答

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; 
 
}
<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通道。

+0

感谢队友,我可能会坚持我目前的状况,但这是一个很好的选择。干杯 –

+0

欢迎您:) –

+0

它看起来不错。但是这个问题是你的'h1'变暗了。 –

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 
}