【问题标题】:RGBA — Alpha channel as a separate classRGBA - Alpha 通道作为一个单独的类
【发布时间】:2018-10-17 09:09:10
【问题描述】:

假设我们有一个存储背景颜色的类列表。

.bgr-red //background-color: rgb(255, 0, 0);
.bgr-green //background-color: rgb(0, 0 , 255);
.bgr-blue //background-color: rgb(0, 128, 0);

我们有一个使用这些类之一的 div。

<div class="bgr-red">...</div>

有什么方法可以创建一组包含 Alpha 通道的新类?类似这样的东西(我试过这个方法,没用):

.alpha-90 //background-color: rgba(inherit, inherit, inherit, .9);
.alpha-80 //background-color: rgba(inherit, inherit, inherit, .8);
.alpha-70 //background-color: rgba(inherit, inherit, inherit, .7);

最终目标是能够将背景颜色不透明度放入与其余背景颜色值分开的 div 中?像这样创建一个 div:

<div class="bgr-red alpha-80">...</div>

谢谢。

【问题讨论】:

  • rgba(inherit, inherit, inherit, .9); 奇怪,如果您需要继承所有内容,为什么不直接使用opacity
  • @BladeMight 因为不透明度也会影响里面的内容
  • 好的。我明白了。

标签: css


【解决方案1】:

使用 CSS 变量:

.bgr-red {
  background-color: rgba(255, 0, 0, var(--a, 1));
}

.bgr-green {
  background-color: rgba(0, 0, 255, var(--a, 1));
}

.bgr-blue {
  background-color: rgba(0, 128, 0, var(--a, 1));
}

.alpha-90 {
  --a: 0.9;
}

.alpha-70 {
  --a: 0.7;
}

.alpha-10 {
  --a: 0.1;
}
<div class="bgr-red">...</div>

<div class="bgr-red alpha-70">...</div>

<div class="bgr-red alpha-10">...</div>

为了获得更好的支持,您可以考虑使用伪元素来创建背景层并调整不透明度:

div {
  position: relative;
  z-index: 0;
}

div::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: -1;
}

.bgr-red::before {
  background-color: rgb(255, 0, 0);
}

.bgr-green::before {
  background-color: rgb(0, 0, 255);
}

.bgr-blue::before {
  background-color: rgb(0, 128, 0);
}

.alpha-90::before {
  opacity: 0.9;
}

.alpha-70::before {
  opacity: 0.7;
}

.alpha-10::before {
  opacity: 0.1;
}
<div class="bgr-red">...</div>

<div class="bgr-red alpha-70">...</div>

<div class="bgr-red alpha-10">...</div>

【讨论】:

    猜你喜欢
    • 2013-06-06
    • 2016-12-01
    • 2018-11-20
    • 1970-01-01
    • 2012-04-02
    • 2019-06-16
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    相关资源
    最近更新 更多