【问题标题】:How to override opacity for a child [duplicate]如何覆盖孩子的不透明度[重复]
【发布时间】:2014-03-20 03:47:21
【问题描述】:

我正在尝试将“演示文本 4”的不透明度重置为 1.0,其中其容器的不透明度设置为 0.3。 我读到我可以直接使用:颜色: RGBA(255, 255, 0, 1); 但这对我不起作用。有没有办法实现我的目标?

<!DOCTYPE html>
<html lang="en">
<head>
<style>
#text_holder {
background: blue;
width: 500px;
height: 200px;
}
#text_holder2 {
background: blue;
width: 500px;
height: 200px;
color: rgba(255, 255, 0, 1);
}

#alpha_30 {
opacity: 0.3;
color: #ff0000;
}
#alpha_100 {
color: #ff0000;
}
</style>
</head>

<body>


<div id="alpha_100">
<div id="text_holder">
    <p>Demo text 1</p>
</div>
</div>

<div id="alpha_30">
<div id="text_holder">
    <p>Demo text 2</p>
</div>
</div>

<div id="alpha_30">
<div id="text_holder">
    <p>Demo text 3</p>
</div>


<div id="text_holder2">
    <p>Demo text 4</p>


</div>

</div>

</body>
</html>

【问题讨论】:

  • 基本上,您不能覆盖孩子的不透明度。您可能正在寻找的答案取决于您实际尝试做的事情。
  • Paulie 是对的,不透明度会影响整个元素(包括子元素)并且不能被子元素反转。你能具体说明你想要做什么吗?有一些方法可以解决它。
  • 我正在尝试创建背景并应用 alpha =.5,然后在背景上放置一些文本,但要在 alpha =1 处显示文本。我知道我可以用图形创建背景,但想看看我是否可以用 CSS 实现相同的效果。
  • 使用 RGBA 代替不透明度的背景颜色/

标签: css


【解决方案1】:

你不能。

如果您使用纯背景色,则可以使用 rgba。

#text_holder {
background:rgba(0, 0, 255,1);
width: 500px;
height: 200px;
}
#text_holder2 {
background: rgba(0, 0, 255,1);;
width: 500px;
height: 200px;
color: rgba(255, 255, 0, 1);
}

#alpha_30 > div {/* select child */
/*opacity: 0.3;*/
background:rgba(0, 0, 255,0.3);/* give opacity to bg color only */
color: #ff0000;
}
#alpha_100 {
color: #ff0000;
}

对于作为背景的图像,您可以通过使用 rgba 中的主要背景颜色来伪造不透明度。如果您希望背景的不透明度为 0.3,则执行 1 -0.3 = 0.7 来设置您的 rgba 不透明度。

<div class="bg-img">
  <p class="text_holder"> some text</p>
</div>
.bg-img {
  background:url(http://lorempixel.com/100/100/abstract);
}
.bg-img .text_holder {
  background:rgba(255,255,255,0.3);/* here white cause body as white background */
  }

这些都可以解决:两者的演示(测试底部的 bg 图像):http://codepen.io/anon/pen/yGgpz

【讨论】:

  • 为什么不能像其他所有属性一样覆盖不透明度?
  • @Lee 你不喜欢如果父母是 display:none;如果父级是 z-index:1,则内部的任何内容都将被隐藏;除了 ^parent 的任何兄弟姐妹之外,任何 position children 的值都不会超过 z-index:1 。级联样式表。第一个词告诉 CSS 是如何工作的。有一些规则可以重置为子项(边框、颜色、背景……),只要它是不依赖于父项布局的特定细节。如果将父母设置为半透明,那么它就是整个盒子,包括孩子,否则规则失去了它的第一个含义。请原谅我的平均英语。
【解决方案2】:

使用rgba(225, 0, 0, .3) 作为父 div。

堆栈片段示例:

.opaque {
  width: 500px;
  height: 500px;
  text-align: center;
  color: black;
  background: rgba(225, 0, 0, .5);
}
&lt;div class="opaque"&gt;This text is not opaque&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 2016-09-28
    • 2013-01-27
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    • 2011-09-24
    • 2011-09-27
    相关资源
    最近更新 更多