与How do I give text or an image a transparent background using CSS?相关, 但略有不同。
我想知道是否可以更改背景图像 的 alpha 值,而不仅仅是颜色。显然我可以只保存具有不同 alpha 值的图像,但我希望能够动态调整 alpha。
到目前为止我得到的最好的是:
<div style="position: relative;">
<div style="position: absolute; left: 0px; right: 0px; top: 0px; bottom: 0px;
background-image: url(...); opacity: 0.5;"></div>
<div style="position: relative; z-index: 1;">
<!-- Rest of content here -->
</div>
</div>
它可以工作,但它笨重且丑陋,并且在更复杂的布局中会把事情弄得一团糟。
最佳答案
你可以用 CSS 生成的内容做褪色的背景
演示在 http://jsfiddle.net/gaby/WktFm/508/
HTML
<div class="container">
contents
</div>
CSS
.container{
position: relative;
z-index:1;
overflow:hidden; /*if you want to crop the image*/
}
.container:before{
z-index:-1;
position:absolute;
left:0;
top:0;
content: url('path/to/image.ext');
opacity:0.4;
}
但是您不能修改不透明度,因为我们不允许修改生成的内容..
虽然您可以使用类和 css 事件来操作它(但不确定它是否符合您的需要)
例如
.container:hover:before{
opacity:1;
}
更新
您可以使用 css 转换来设置不透明度的动画(再次通过类)
演示在 http://jsfiddle.net/gaby/WktFm/507/
添加
-webkit-transition: opacity 1s linear;
-o-transition: opacity 1s linear;
-moz-transition: opacity 1s linear;
transition: opacity 1s linear;
.container:before
规则将使不透明度在一秒内变为 1。
兼容性
- FF 5(也可能是 4,但没有安装它。)
- IE 9 失败..
- 基于 Webkit 的浏览器失败(Chrome 现在支持它 v26 - 可能也支持更早的版本,但只是检查了我当前的版本),但他们知道并正在努力(https://bugs.webkit.org/show_bug.cgi?id=23209)<
.. 所以目前只有最新的 FF 支持它.. 但这是个好主意,不是吗? :)
关于html - CSS 背景图像不透明度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6890218/