简体   繁体   中英

Allow opacity on container but not child elements

Basically, I have a div with background set to an image and opacity of 0.5 . Inside the div , I am trying to place the same img as a circle. However, it gets the 0.5 opacity too.

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. Answer by Michael_B is better in this case.

Update

A better explanation is available at this SO post .

Original

opacity is applied to the full sub-tree. If you don't want it to be applied to child element, you can use rgba syntax as suggested by MDN .

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

With opacity , the effect applies to the entire element, including child elements and content.

From 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() .

The rgba() rule allows for the opacity to be set via the alpha channel.

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); } , and that would set the opacity to 0.5 on the background-color alone. Child elements would be unaffected.

Learn more here: A brief introduction to Opacity and RGBA

If using an image is a must, see these posts:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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