基本上,我有一个div
,背景设置为图像,opacity
为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:
该值适用于整个元素,包括其内容,
即使该值不是子元素继承的。因此,
元素及其包含的子元素都具有相同的不透明度
到元素的背景,即使元素及其子元素具有
彼此之间有不同的混浊。
此规则的例外是使用background-color
设置的rgba()
。rgba()
规则允许通过alpha通道设置opacity
。
因此,您可以将父级设置为div { background-color: rgba (0, 255, 255, 0.5); }
,并且仅在opacity
上将0.5
设置为background-color
。子元素将不受影响。
在此处了解更多信息:A brief introduction to Opacity and RGBA
如果必须使用图像,请参阅以下文章:
Can I set an opacity only to the background image of a div?
CSS: set background image with opacity?