css – 允许容器上的不透明度,但不允许子元素

前端之家收集整理的这篇文章主要介绍了css – 允许容器上的不透明度,但不允许子元素前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
基本上,我有一个div,背景设置为图像,不透明度为0.5.在div中,我试图将同样的img放在一个圆圈中.但是,它也获得0.5不透明度.

有什么好方法可以确保不会发生这种情况?

<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,@H_404_14@ even though the value is not inherited by child elements. Thus,an@H_404_14@ element and its contained children all have the same opacity relative@H_404_14@ to the element’s background,even if the element and its children have@H_404_14@ different opacities relative to one another.

此规则的例外是使用rgba()设置背景颜色.

rgba()规则允许通过alpha通道设置不透明度.

所以你可以将父设置为div {background-color:rgba(0,255,0.5); },这将仅在背景颜色上将不透明度设置为0.5.子元素不受影响.

在这里了解更多:A brief introduction to Opacity and RGBA

如果必须使用图像,请参阅以下帖子:

> Can I set an opacity only to the background image of a div?@H_404_14@> CSS: set background image with opacity?

猜你在找的CSS相关文章