如何在不影响文本颜色的情况下使背景图像变暗?
http://jsfiddle.net/tx58qf3m/
div {
display:block;
background:url('http://placehold.it/500x500') 0 0 no-repeat;
background-color:rgba(0, 0, 0, 1);
background-size:cover;
height:500px;
width:500px
}
<div>
<h1>Hello, it's me!</h1>
</div>
使用:before
div {
display:block;
background:url('http://placehold.it/500x500') 0 0 no-repeat;
background-color:rgba(0, 0, 0, 1);
background-size:cover;
height:500px;
width:500px
}
div:before {
content: "";
position: absolute;
width: 100%;
height: 100%;
opacity: .4;
z-index: 1;
background-color:black
}
http://jsfiddle.net/tx58qf3m/14/
如您所见,更改父元素的opacity
将影响子元素,即您的示例中的h1
。
您有几个不同的选项可以在不影响子元素的情况下完成此操作。
1) 在图像编辑器中编辑opacity
(显而易见,代码量最少)
2) 使用伪元素来包含背景图像,并在那里更改opacity
-DEMO
3) 与其将background-image
应用于div
,不如制作另一个子元素来包含图像-DEMO
不要忘记调整您的z-index
值。
像这个
<style>
Div {
Position:relative;
}
Div:before {
Content:'';
Position:absolute;
Top:0;
Left:0;
Background-color:rgba (0,0,0,.5);
Width:100%;
Height:100%;
Z-index:2;
}
Div H2 {
Position:relative;
Z-index:3;
}
</style>