css 中的背景颜色继承

Background-color inheritence in css

我想知道是否有可能使用继承创建两个颜色相同但不透明度不同的 div。

据我所知,这是不可能的。至少没有我猜的错误。

如果我设置正常的 rgb 颜色并赋予它不透明度并且在内部 div 继承背景颜色并且不设置不透明度它不会起作用。

#outside { background-color: #96B4DC; opacity: 0.5; }
#outside > * { opacity: 1; }
.inside { background-color: inherit; }

看起来像这样:https://jsfiddle.net/s6pandof/5/

所以我尝试了其他选项,对我来说最简单的是 rgba。所以我只是设置颜色,继承,并在想更多的东西,但它让我感到惊讶。内部 div 没有不透明度。所以它成功了。

#outside { background-color: rgba(150, 180, 220, 0.5); }
.inside { background-color: inherit; }

你可以在那里看到它:https://jsfiddle.net/s6pandof/6/

我在 Ubuntu 中的 Firefox 43.0 以及 Android 中的相同版本和 Android 中的 Chrome 47.0.2526.83 中尝试过它,每个都显示它这样。

我的问题是 - 这种行为是否正确?因为它似乎肯定不是。如果不是,是否有任何其他可能使 inside div 从 outside div 继承颜色,但设置背景颜色完全不透明?

这对我来说似乎是正确的行为。从经验谈起,而不是从文档谈起。

我已经在我的 OSX Firefox 43 和 Chrome 47.0.2526.106 上试过了。

My question is - Is this behaviour correct?

当然:您所做的只是将一种半透明背景颜色叠加在另一种颜色之上。想象一下,将一张 sheet 彩色玻璃纸叠加在另一张上面:sheet 重叠的区域看起来更不透明。是一样的效果。

如您指定的那样,外部元素的 rgba(150, 180, 220, 0.5) 由内部元素继承,因此您有两层该背景色。

background-color: alpha 通道继承行为是正确的。

一个半透明 <div> 与另一个半透明 <div> 重叠。

您看到的 div#inside 背景是 组合 半透明。

见下面的演示:

div {
position: relative;
}

p {
position: absolute;
top: 0;
left: 0;
margin: 0;
}

div[id^='outside'] {
width: 100%;
height: 100px;
}

div[id^='inside'] {
width: 50%;
height: 100%;
margin: 0 auto;
}

#outside1 {
background-color: rgba(150, 180, 220, 0.5);
}

#outside2 {
background-color: rgba(150, 180, 220, 0.4);
}

#outside3 {
background-color: rgba(150, 180, 220, 0.3);
}

#outside4 {
background-color: rgba(150, 180, 220, 0.2);
}

#outside5 {
background-color: rgba(150, 180, 220, 0.1);
}

#inside1, #inside2, #inside3, #inside4, #inside5 {
background-color: inherit;
}
<div id="outside1">
<p>Outside 1 (0.5)</p>
<div id="inside1"><p>Inside 1 (0.5 + 0.5)</p></div>
</div>

<div id="outside2">
<p>Outside 2 (0.4)</p>
<div id="inside2"><p>Inside 2 (0.4 + 0.4)</p></div>
</div>

<div id="outside3">
<p>Outside 3 (0.3)</p>
<div id="inside3"><p>Inside 3 (0.3 + 0.3)</p></div>
</div>

<div id="outside4">
<p>Outside 4 (0.2)</p>
<div id="inside4"><p>Inside 4 (0.2 + 0.2)</p></div>
</div>

<div id="outside5">
<p>Outside 5  (0.1)</p>
<div id="inside5"><p>Inside 5 (0.1 + 0.1)</p></div>
</div>