css - 允许容器不透明但不允许子元素

标签 css

基本上,我有一个 div,背景设置为图像,不透明度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 :

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.

此规则的异常(exception)是使用 rgba() 设置的 background-color

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

所以你可以将父级设置为 div { background-color: rgba (0, 255, 255, 0.5); },这将单独在 background-color 上将 opacity 设置为 0.5。子元素将不受影响。

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

如果必须使用图片,请参阅这些帖子:

关于css - 允许容器不透明但不允许子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45557426/

相关文章:

javascript - table 上的 Canvas ,奇怪的填充

javascript - 如何使用Brackets在搜索引擎上发布网站?

html - 在 div 内垂直居中输入

css - 你能在 CSS 中设置边框不透明度吗?

jquery - 在一定宽度下停止滚动菜单

css - 将 "padding"添加到div的外部?

css - 移动端横向溢出

html - Owl Carousel : first slide not trigger action

html - 内联 block 元素换行时的CSS,父包装器不适合新宽度

javascript - 创建接管页面