【问题标题】:Override opaque text in a transparent div with CSS使用 CSS 覆盖透明 div 中的不透明文本
【发布时间】:2011-01-23 07:46:39
【问题描述】:

我正在尝试使透明 div 中的文本没有不透明度,也就是完全黑色:

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

这可能只使用 CSS 吗?

提前致谢

【问题讨论】:

  • +1 JabbR 把我带到了这里。

标签: html overriding css opacity


【解决方案1】:

最简单的方法是使用 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 */
}

但是,这与 IE 不兼容。

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

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

我记得 IE

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

【讨论】:

  • 总是声明没有 RGBa 的回退,就像我在回答中链接到的文章中所述。
  • @Marcel Korpel,是的,你是对的(并使用后备进行编辑)。
  • @ricebowl:不,这会触发 IE 6/7 中的错误:css-tricks.com/ie-background-rgb-bug
  • @Marcel Korpel,阅读了您链接到的页面后,我没有看到 IE6 中的错误。在指定一个它似乎对我不起作用的值之前指定一个它理解的值(IE6 在工作中,在 XP sp3 上)... =/
  • 哦,是的。我在测试中使用了background 而不是background-color。我的错。
【解决方案2】:

子元素继承不透明度。您可以做的是将 &lt;p&gt; 定位在不透明 div 之外,并设置负边距以将其移动到上面。

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

【讨论】:

    【解决方案3】:

    背景是否由纯色组成?如果是这样,您还可以使用 RGBa 为 div 选择不被其子级继承的透明背景颜色。阅读RGBa Browser Support 了解更多信息、IE 的解决方法和another solution

    如果div 的背景不是实心的,您可以使用透明的PNG 作为背景。请记住在 IE6(和 5.5)中使用 AlphaImageLoader。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-10
      • 2016-09-28
      • 2011-01-25
      • 2011-06-21
      • 1970-01-01
      • 1970-01-01
      • 2016-11-12
      相关资源
      最近更新 更多