我有以下代码以使背景图像变暗。带有背景图像的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 :(得分: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;
}
&#13;
<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>
&#13;
编辑:伪元素下面的文字不再受叠加分别Alpha通道的影响。
答案 1 :(得分: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
}