【问题标题】:Separating background-color and opacity?分离背景颜色和不透明度?
【发布时间】:2019-08-21 20:48:00
【问题描述】:

有没有办法在一个地方设置元素的 bg 颜色并在其他地方操纵它的不透明度?

我知道这可以通过透明 PNG 或一些堆叠的 DIV 来完成,但我不能使用这些选项(请不要浪费时间建议它们)。

CSS 文件 A

#menubar {
background-color: #036564;
}

CSS 文件 B

#menubar {
background-color-opacity: 0.5; /* idea 1 */
background-color: rgba(inherit, inherit, inherit, 0.5); /* idea 2 */
}

【问题讨论】:

  • 为什么需要单独的背景色不透明度。 rgba 是有史以来最好的解决方案
  • @sandeep:这里的想法是他在一个文件中指定 RGB 值,并且不想在另一个文件中使用 A 值重复它们。
  • @sandeep:如果您需要使用 JavaScript 动态设置元素的背景不透明度,但又不想在 JavaScript 代码中包含颜色值(它们当然不属于),则需要此功能.

标签: css


【解决方案1】:

目前无法在 CSS 中指定部分颜色分量并让其余值继承或级联。

如果您需要使用 alpha 值指定颜色,则必须将其 RGB 或 HSL 值与 alpha 一起提供,因为唯一允许您指定 alpha 分量的颜色值是 rgba() 和 @ 987654323@。您不能独立于其他颜色分量指定 alpha。

详情请参阅CSS3 Color Module

【讨论】:

  • 谢谢,我知道,但我觉得这里面有一些特斯拉魔法;)也感谢拼写更正。
【解决方案2】:

如果你使用 Sass,你可以为 rgb 颜色定义一个变量,然后将它插入到一个 rgba 颜色中,只指定 alpha 透明度分量。

$base-color: rgb(200,150,100);

a {
  color: rgba( $base-color, .7 );
}

发现于https://robots.thoughtbot.com/controlling-color-with-sass-color-functions

【讨论】:

  • 虽然问题根本不是关于“Sass”的,但你的答案在这里不正确......无论如何我要花点时间+1!欢迎来到 SO - 很高兴有你。
【解决方案3】:

您实际上可以将两者分开:background-coloropacity,但在这种情况下,opacity 应用于整个元素,而不仅仅是背景颜色。

http://jsfiddle.net/tUHdv/

在 jsfiddle 示例中,请注意蓝色方块中的字母是如何变红的。

注意:添加此答案是为了阐明您可以同时使用这两个属性,但它影响的不仅仅是background-color

【讨论】:

  • 谢谢,但就像你说的 - 不透明度适用于整个元素。
【解决方案4】:

分别改变背景颜色和不透明度

这是我们的场景:我们有一些元素,我们想从 CSS 中单独更改背景颜色和不透明度:

div {
  width: 200px;
  height: 150px;
  background-color: rgb(120, 200, 200);
}
<div>
  This element has a background color... We want to change the background color and opacity separately, but without changing the opacity of this text.
</div>

opacity: 0.5; 浮现在脑海,但是当我们尝试它时,我们注意到元素内容也变得部分透明。这不是我们想要的:

div {
  width: 200px;
  height: 150px;
  background-color: rgb(120, 200, 200);
  opacity: 0.5;
}
<div>
  This element has a background color... We want to change the background color and opacity separately, but without changing the opacity of this text.
</div>

使用伪元素

我们可以在 div 中插入一个伪元素,正确定位和调整它的大小,然后在其上设置背景颜色和不透明度:

div {
  width: 200px;
  height: 150px;
}

div::before {
  content: " ";
  display: block;
  width: 200px;
  height: 150px;
  position: absolute;
  z-index: -1; 

  /* The magic is here! */
  background-color: rgb(120, 200, 200);
  opacity: 0.5;
}
<div>
  This element has a background color... We want to change the background color and opacity separately, but without changing the opacity of this text.
</div>

当然,这只是一种解决方法。但在许多情况下,这可以帮助您实现您想要的。

我们真正需要的是一些花哨的 CSS 函数来处理颜色,这样我们就可以做到:

div {
  --bg: rgb(120,200,200);
  --alpha: 0.5;

  background: rgba(r(--bg), g(--bg), b(--bg), var(--alpha));
}

但是,唉,AFAIK 它不存在(还)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-05
    • 2017-03-15
    • 1970-01-01
    • 2015-02-10
    • 2014-03-22
    • 2017-08-11
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多