简体   繁体   English

允许容器不透明,但不允许子元素

[英]Allow opacity on container but not child elements

Basically, I have a div with background set to an image and opacity of 0.5 . 基本上,我有一个div ,背景设置为image, opacity0.5 Inside the div , I am trying to place the same img as a circle. div内部,我试图将相同的img放置为一个圆。 However, it gets the 0.5 opacity too. 但是,它的opacity也为0.5。

What is a good way to make sure this doesn't happen? 确保这种情况不会发生的好方法是什么?

<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;
}

Update The rgba syntax does not work for background image. 更新 rgba语法不适用于背景图像。 Answer by Michael_B is better in this case. 在这种情况下, Michael_B的回答会更好。

Update 更新资料

A better explanation is available at this SO post . 此SO帖子中有更好的解释。

Original 原版的

opacity is applied to the full sub-tree. opacity应用于整个子树。 If you don't want it to be applied to child element, you can use rgba syntax as suggested by MDN . 如果不希望将其应用于子元素,则可以使用MDN建议的 rgba语法。

Example: background: rgba(0, 0, 0, 0.6) url(<your_url>); 示例: background: rgba(0, 0, 0, 0.6) url(<your_url>);

With opacity , the effect applies to the entire element, including child elements and content. 使用opacity ,效果将应用于整个元素,包括子元素和内容。

From MDN : 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. 因此,一个元素及其包含的子元素相对于元素的背景都具有相同的不透明度,即使该元素及其子元素相对于彼此具有不同的不透明度。

The exception to this rule is background-color set with rgba() . 该规则的例外是使用rgba()设置background-color

The rgba() rule allows for the opacity to be set via the alpha channel. rgba()规则允许通过alpha通道设置opacity

So you could set the parent to div { background-color: rgba (0, 255, 255, 0.5); } 因此,您可以将父级设置为div { background-color: rgba (0, 255, 255, 0.5); } div { background-color: rgba (0, 255, 255, 0.5); } , and that would set the opacity to 0.5 on the background-color alone. div { background-color: rgba (0, 255, 255, 0.5); } ,这会将单独的background-coloropacity设置为0.5 Child elements would be unaffected. 子元素将不受影响。

Learn more here: A brief introduction to Opacity and RGBA 在此处了解更多信息: 不透明度和RGBA的简要介绍

If using an image is a must, see these posts: 如果必须使用图像,请参阅以下文章:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM