如何在 CSS 中设置背景图像不透明度而不使用伪之前/之后和/或定位的 div

我有一个由 CMS 生成的 div,其中包含一个背景图像,我想更改该背景图像的不透明度,而不影响该 div 子元素的不透明度。


https://jsfiddle.net/L5b81yqo/


超文本标记语言


<div class="container">

    <p>Some dummy text</p>

</div>

CSS


.container {

  background: url(https://live.staticflickr.com/4561/38054606355_26429c884f_b.jpg);

  width: 100%;

  height: 500px;

  background-size: cover;

}

是否可以使用CSS更改背景图像的不透明度,而无需在之前/之后使用psuedo(因为这涉及使用背景URL,我无法在样式表中使用它,因为它是来自CMS的动态并且可以是任何URL)或添加附加标记(因为 CMS 不允许我添加更多标记)。


我查看了各种解决方案,但所有这些似乎都使用了我无法使用上面定义的方法,例如https://scotch.io/tutorials/how-to-change-a-css-background-images-opacity


如果不可能,那也没关系,我可以寻找解决方法。


跃然一笑
浏览 91回答 3
3回答

慕田峪7331174

在之前/之后不使用 psuedo (因为这涉及使用后台 URL,我无法在样式表中使用它,因为它是来自 CMS 的动态并且可以是任何 URL您仍然可以使用伪元素并继承背景,而不需要 url:.container {&nbsp; /* I will not touch this */&nbsp; background: url(https://live.staticflickr.com/4561/38054606355_26429c884f_b.jpg);&nbsp;&nbsp; /**/&nbsp; height: 400px;&nbsp; background-size: 0 0; /* make the main background hidden */&nbsp; position:relative;&nbsp; z-index:0;}.container::before {&nbsp; content:"";&nbsp; position:absolute;&nbsp; top:0;&nbsp; left:0;&nbsp; right:0;&nbsp; bottom:0;&nbsp; z-index:-1;&nbsp; background-image:inherit;&nbsp; background-size:cover;&nbsp; opacity:0.3;}<div class="container">&nbsp; &nbsp; <p>Some dummy text</p></div>或者如下所示,在顶部有一个简单的背景颜色层:.container {&nbsp; /* I will not touch this */&nbsp; background: url(https://live.staticflickr.com/4561/38054606355_26429c884f_b.jpg);&nbsp;&nbsp; /**/&nbsp; background-size:cover;&nbsp; height: 400px;&nbsp; position:relative;&nbsp; z-index:0;}.container::before {&nbsp; content:"";&nbsp; position:absolute;&nbsp; top:0;&nbsp; left:0;&nbsp; right:0;&nbsp; bottom:0;&nbsp; z-index:-1;&nbsp; background:rgba(255,255,255,0.7);}<div class="container">&nbsp; &nbsp; <p>Some dummy text</p></div>

PIPIONE

.container {&nbsp; background: url(https://live.staticflickr.com/4561/38054606355_26429c884f_b.jpg);&nbsp; width: 100%;&nbsp; height: 500px;&nbsp; background-size: cover;&nbsp; background-color: rgba(255, 255, 255, 0.5);&nbsp; background-blend-mode: color;}<div class="container">&nbsp; &nbsp; <p>Some dummy text</p></div>您可以使用 Banckground-color: rgba(rbg 中的颜色,不透明度) 然后使用 background-blend-mode: color; 来完成此操作 就是这个

慕森王

您可以使用以下方法实现此目的background-blend-modebackground-blend-mode可以使用background-color,没有background-color则不行.container {&nbsp; background: url(https://live.staticflickr.com/4561/38054606355_26429c884f_b.jpg);&nbsp; width: 100%;&nbsp; height: 500px;&nbsp; background-size: cover;&nbsp; background-color: rgba(238, 238, 238, 0.81);&nbsp; background-blend-mode: color;}<div class="container">&nbsp; <p>Some dummy text</p></div>注意:这不会完全像不透明度一样工作,但它与不透明度类似
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5