简体   繁体   English

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

[英]Override opaque text in a transparent div with CSS

I am trying to make text inside a transparent div have no opacity, aka be completely black: 我试图让透明div内的文字没有不透明度,也就是说完全是黑色的:

<div style="opacity:0.6;background:#3cc;">
    <p style="background:#000;opacity:1">This text should be all black</p>
</div>

Is this possible to do with only CSS? 这可能只与CSS有关吗?

Thanks in advance 提前致谢

The easiest way is to style the background of the parent div with opacity/alpha: 最简单的方法是使用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 */
}

This is not, however, compatible with IE. 但是,这与IE不兼容。

For IE >= 7 compatibility, you could use: 对于IE> = 7兼容性,您可以使用:

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

I recall that IE < 7 has a proprietary filter option, but I'm afraid I can't recall how it works. 我记得IE <7有一个专有的过滤器选项,但我担心我不记得它是如何工作的。 So I've omitted any attempt to describe/show it. 所以我省略了任何描述/展示它的尝试。 If I can find a useful reference though I'll add it in later. 如果我能找到一个有用的参考,虽然我会在以后添加它。

As noted by easwee the opacity is inherited by contained elements, which is why you can't override it, and is why I prefer to use the background-color / background-image approach. 正如所指出的那样,不透明度是由包含的元素继承的,这就是为什么你不能覆盖它,这就是为什么我更喜欢使用background-color / background-image方法。

The child elements inherit the opacity. 子元素继承不透明度。 What you could do is to position the <p> outside the opaque div and set a negative margin to move it over it. 你可以做的是将<p>放在不透明的div之外,并设置一个负边距来移动它。

I came across this problem often and usually solved it like this. 我经常遇到这个问题,通常会像这样解决它。 Problem is only when you have dynamic content and the div has to expand. 问题是只有当你有动态内容并且div必须扩展时。

Does the background consist of a solid colour? 背景是否由纯色组成? If so, you could also use RGBa to select a transparent background colour for the div that isn't inherited by its the children. 如果是这样,您还可以使用RGBa为div选择透明背景颜色,而不是其子项继承的div Read RGBa Browser Support for more information, a workaround for IE and another solution . 阅读RGBa浏览器支持以获取更多信息,IE的解决方法和其他解决方案

If the background of the div isn't solid, you can use a transparent PNG as background. 如果div的背景不是实心,则可以使用透明PNG作为背景。 Remember to use AlphaImageLoader in IE6 (and 5.5). 记得在IE6(和5.5)中使用AlphaImageLoader。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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