您不能用CSS更改background-image
的不透明度。但是,有办法达到同样的结果。
Method 1
此方法使用:这是绝对定位其父内部伪类后。在伪元素上设置背景图像以及不透明度,使背景不透明度设置在背景上。
HTML
<div>
Text on top, no big deal, no big deal. Just a little text and stuff. That's all.
</div>
CSS
div {
width:320px;
height:374px;
display: block;
position: relative;
border: solid 1px #f00;
}
div::after {
content: "";
background-image: url('http://placehold.it/800x600');
background-size: cover;
background-repeat: no-repeat;
opacity: 0.5;
top: 0;
left: 0;
bottom: 0;
right: 0;
position: absolute;
z-index: -1;
}
如果您需要向后兼容性,您需要在您的标记额外的元素来达到同样的结果:
HTML
<div class="container">
<div class="background"></div>
Text on top, no big deal, no big deal. Just a little text and stuff. That's all.
</div>
CSS
.container {
width:320px;
height:374px;
display: block;
position: relative;
border: solid 1px #f00;
}
.container .background {
content: "";
background-image: url('http://placehold.it/800x600');
background-size: cover;
background-repeat: no-repeat;
opacity: 0.5;
top: 0;
left: 0;
bottom: 0;
right: 0;
position: absolute;
z-index: -1;
}
这里是一个伟大的文章,以达到相同的结果的CSS3方法:
http://css-tricks.com/snippets/css/transparent-background-images/
示例 - '背景色: rgba(0,0,0,0.5);' – Vucko 2014-09-29 07:59:45
可以按照以下链接进行回答: - http:/ /stackoverflow.com/questions/7241341/can-i-set-an-opacity-only-to-the-background-image-of-a-div – Puneet 2014-09-29 08:02:12
这是一个很好的问题,我认为它太多了。但我没有一个合适的答案。我使用两个'div'来实现它。一个包含内容文本,另一个包含背景图像。 – 2014-09-29 08:03:14