Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
757 views
in Technique[技术] by (71.8m points)

css - 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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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); }, 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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...