基本上,我有一个 div
,背景设置为图像,不透明度
为 0.5
。在 div
中,我试图将相同的 img
放置为一个圆圈。但是,它也获得了 0.5 的 opacity
。
什么是确保这种情况不会发生的好方法?
<div class="bg-img" ng-style="{'background':'url({{vm.large}}) center / cover'}">
<img ng-src="{{vm.large}}">
</div>
.bg-img {
height: 140px;
position: relative;
opacity: 0.6;
}
.bg-img img {
width: 100px;
height: 100px;
border-radius: 50%;
position: absolute;
}
最佳答案
与 opacity
,效果适用于整个元素,包括子元素和内容。
来自 MDN :
The value applies to the element as a whole, including its contents, even though the value is not inherited by child elements. Thus, an element and its contained children all have the same opacity relative to the element's background, even if the element and its children have different opacities relative to one another.
此规则的异常(exception)是使用 rgba()
设置的 background-color
。
rgba()
规则允许通过 alpha channel 设置不透明度
。
所以你可以将父级设置为 div { background-color: rgba (0, 255, 255, 0.5); }
,这将单独在 background-color
上将 opacity
设置为 0.5
。子元素将不受影响。
在这里了解更多:A brief introduction to Opacity and RGBA
如果必须使用图片,请参阅这些帖子:
关于css - 允许容器不透明但不允许子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45557426/