使用CSS覆盖透明div中的不透明文本

mag*_*ger 14 html css overriding opacity css3

我试图让透明div内的文字没有不透明度,也就是说完全是黑色的:

<div style="opacity:0.6;background:#3cc;">
    <p style="background:#000;opacity:1">This text should be all black</p>
</div>
Run Code Online (Sandbox Code Playgroud)

这可能只与CSS有关吗?

提前致谢

Dav*_*mas 13

最简单的方法是使用opacity/alpha设置父div的背景样式:

div  {
    background: #fff; /* for browsers that don't understand the following rgba rule */
    background-color: rgba(255,255,255,0.5); /* rgb, white, with alpha at 0.5 */
}
Run Code Online (Sandbox Code Playgroud)

但是,这与IE不兼容.

对于IE> = 7兼容性,您可以使用:

div  {
    background-image: url('path/to/partially_transparent.png');
    background-position: 0 0;
    background-repeat: repeat;
}
Run Code Online (Sandbox Code Playgroud)

我记得IE <7有一个专有的过滤器选项,但我担心我不记得它是如何工作的.所以我省略了任何描述/展示它的尝试.如果我能找到一个有用的参考,虽然我稍后会添加它.

正如easywee所指出的那样,不透明度是由包含的元素继承的,这就是为什么你不能覆盖它,这就是为什么我更喜欢使用background-color/ background-image方法.


eas*_*wee 3

子元素继承不透明度。您可以做的是将<p>不透明 div 的外部定位并设置负边距以将其移动到其上方。

我经常遇到这个问题,通常都是这样解决的。仅当您有动态内容并且 div 必须扩展时才会出现问题。