我正在设计一个电子应用程序,所以我可以访问CSS变量。我在vars.css中定义了一个颜色变量:

:root {
  --color: #f0f0f0;
}

我想在main.css中使用这个颜色,但是使用了一些不透明度:

#element {
  background: (somehow use var(--color) at some opacity);
}

我该怎么做呢?我没有使用任何预处理器,只有CSS。我更喜欢全css的答案,但我将接受JavaScript/jQuery。

我不能使用不透明,因为我使用的背景图像不应该是透明的。


当前回答

第一次在这里发帖。

一个简单的JavaScript解决方案

下面是一个简单的JavaScript函数,可以为命名颜色(如“红色”)添加透明度

虽然. setfillcolor()被贬低了,但它仍然在一些浏览器中实现(blink和webkit)。如果setFillColor()被完全丢弃,希望那时我们会有相对颜色语法。

function addTransparency(color, alpha) {
  const ctx = document.createElement('canvas').getContext('2d');
  ctx.setFillColor(color, alpha);
  return ctx.fillStyle;
}

CSS变量的使用

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Transparency to a Color</title>
<style>
:root {
  --color: lime;
  --alpha: 0.5;
}
.test {
  background-color: var(--color);
}
</style>
</head>
<body class='test'>
<script>
try{"use strict" 

/* Use the getComputedStyle() method to get the current value of the CSS variable --color and the --alpha variable. */

const color = getComputedStyle(document.documentElement).getPropertyValue('--color')||'white'; //added fallback to color white
const alpha = getComputedStyle(document.documentElement).getPropertyValue('--alpha')||1; //added fallback to solid color value of 1

/* Call the addTransparency() function with the color and alpha values as arguments, and store the result in a variable. */

const transparentColor = addTransparency(color, alpha);

/* Use the setProperty() method of the CSSStyleDeclaration interface to set the value of the --color CSS variable to the value of the transparentColor variable. */

document.documentElement.style.setProperty('--color', transparentColor);


function addTransparency(color, alpha) {
  const ctx = document.createElement('canvas').getContext('2d');
  ctx.setFillColor(color, alpha);
  return ctx.fillStyle;
}

}catch(e){document.write(e);}
</script>
</body>
</html>

啊,页面刷新,我失去了我输入的一切,张贴草稿保存。

其他回答

对于使用rgba()与一般css变量,尝试这样做:

在:root内部声明颜色,但不要像其他答案那样使用rgb()。只需要写值

:根{ ——color: 255,0,0; }

使用——color变量使用var()作为其他答案

#某个元素{ 颜色:rgba(var(——Color),0.5); }

SCSS / sass

优点:你可以只使用十六进制颜色值,而不是为每个通道(0-255)使用8位。

这是我最初的想法:https://codyhouse.co/blog/post/how-to-combine-sass-color-functions-and-css-variables

编辑:你也可以修改alpha函数,只使用#{$color-name}-rgb,省略生成的*-r, *-g, *-b CSS变量。


结果

body {
  --main-color: rgb(170, 68, 204);
  --main-color-rgb: 170,68,204;
  --main-color-r: 170;
  --main-color-g: 68;
  --main-color-b: 204;
}

.button-test {
  // Generated from the alpha function
  color: rgba(var(--main-color-r), var(--main-color-g), var(--main-color-b), 0.5);
  // OR (you wrote this yourself, see usage)
  color: rgba(var(--main-color-rgb), 0.5);
}

用法:

body {
    @include defineColorRGB(--main-color, #aa44cc);
}

.button-test {
  // With alpha function:
  color: alpha(var(--main-color), 0.5);
  // OR just using the generated variable directly
  color: rgba(var(--main-color-rgb), 0.5);
}

Mixin和函数

@mixin defineColorRGB($color-name, $value) {
    $red: red($value);
    $green: green($value);
    $blue: blue($value);
    #{$color-name}: unquote("rgb(#{$red}, #{$green}, #{$blue})");
    #{$color-name}-rgb: $red,$green,$blue;
    #{$color-name}-r: $red;
    #{$color-name}-g: $green;
    #{$color-name}-b: $blue;
}

// replace substring with another string
// credits: https://css-tricks.com/snippets/sass/str-replace-function/
@function str-replace($string, $search, $replace: '') {
    $index: str-index($string, $search);
    @if $index {
        @return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
    }
    @return $string;
}

@function alpha($color, $opacity) {
    $color: str-replace($color, 'var(');
    $color: str-replace($color, ')');
    $color-r: var(#{$color+'-r'});
    $color-g: var(#{$color+'-g'});
    $color-b: var(#{$color+'-b'});
    @return rgba($color-r, $color-g, $color-b, $opacity);
}

第一次在这里发帖。

一个简单的JavaScript解决方案

下面是一个简单的JavaScript函数,可以为命名颜色(如“红色”)添加透明度

虽然. setfillcolor()被贬低了,但它仍然在一些浏览器中实现(blink和webkit)。如果setFillColor()被完全丢弃,希望那时我们会有相对颜色语法。

function addTransparency(color, alpha) {
  const ctx = document.createElement('canvas').getContext('2d');
  ctx.setFillColor(color, alpha);
  return ctx.fillStyle;
}

CSS变量的使用

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Transparency to a Color</title>
<style>
:root {
  --color: lime;
  --alpha: 0.5;
}
.test {
  background-color: var(--color);
}
</style>
</head>
<body class='test'>
<script>
try{"use strict" 

/* Use the getComputedStyle() method to get the current value of the CSS variable --color and the --alpha variable. */

const color = getComputedStyle(document.documentElement).getPropertyValue('--color')||'white'; //added fallback to color white
const alpha = getComputedStyle(document.documentElement).getPropertyValue('--alpha')||1; //added fallback to solid color value of 1

/* Call the addTransparency() function with the color and alpha values as arguments, and store the result in a variable. */

const transparentColor = addTransparency(color, alpha);

/* Use the setProperty() method of the CSSStyleDeclaration interface to set the value of the --color CSS variable to the value of the transparentColor variable. */

document.documentElement.style.setProperty('--color', transparentColor);


function addTransparency(color, alpha) {
  const ctx = document.createElement('canvas').getContext('2d');
  ctx.setFillColor(color, alpha);
  return ctx.fillStyle;
}

}catch(e){document.write(e);}
</script>
</body>
</html>

啊,页面刷新,我失去了我输入的一切,张贴草稿保存。

这在CSS中确实是可行的。它只是有点脏,你必须使用渐变。我已经编写了一个小片段作为示例,请注意,对于深色背景,你应该使用黑色不透明度,对于浅色背景-白色背景。

:root { --red: rgba(255, 0, 0, 1); --white-low-opacity: rgba(255, 255, 255, .3); --white-high-opacity: rgba(255, 255, 255, .7); --black-low-opacity: rgba(0, 0, 0, .3); --black-high-opacity: rgba(0, 0, 0, .7); } div { width: 100px; height: 100px; margin: 10px; } .element1 { background: linear-gradient(var(--white-low-opacity), var(--white-low-opacity)) no-repeat, linear-gradient(var(--red), var(--red)) no-repeat; } .element2 { background: linear-gradient(var(--white-high-opacity), var(--white-high-opacity)) no-repeat, linear-gradient(var(--red), var(--red)) no-repeat; } .element3 { background: linear-gradient(var(--black-low-opacity), var(--black-low-opacity)) no-repeat, linear-gradient(var(--red), var(--red)) no-repeat; } .element4 { background: linear-gradient(var(--black-high-opacity), var(--black-high-opacity)) no-repeat, linear-gradient(var(--red), var(--red)) no-repeat; } <div class="element1">hello world</div> <div class="element2">hello world</div> <div class="element3">hello world</div> <div class="element4">hello world</div>

你不能获取一个现有的颜色值并应用alpha通道。也就是说,你不能使用一个现有的十六进制值,如#f0f0f0,给它一个alpha组件,并将结果值与另一个属性一起使用。

然而,自定义属性允许您将十六进制值转换为rgba()使用的RGB三元组,将该值存储在自定义属性中(包括逗号!),使用var()将该值替换为rgba()函数与您想要的alpha值,它将工作:

:根{ /* #f0f0f0十进制RGB */ ——颜色:240、240、240; } 身体{ 颜色:# 000; background - color: # 000; } #{元素 Background-color: rgba(var(——color), 0.8); } <p id="element">如果你能看到这个,说明你的浏览器支持自定义属性

这似乎好得令人难以置信它是如何工作的?

神奇之处在于,自定义属性的值被替换,就像在属性值中替换var()引用时一样,在计算该属性值之前。这意味着就自定义属性而言,示例中的——color值根本不是颜色值,直到某个地方出现了需要颜色值的var(——color)表达式(并且仅在该上下文中)。css-variables规范第2.1节:

自定义属性所允许的语法非常宽松。< declarations -value>结果匹配一个或多个令牌的任何序列,只要该序列不包含<bad-string-token>, <bad-url-token>, unmatched <)-token>, <]-token>,或<}-token>,或顶级<分号-token>令牌或< delimi -token>值为"!"的令牌。

例如,下面是一个有效的自定义属性: ——foo: if(x > 5) this。宽度= 10; 虽然这个值作为变量显然是无用的,因为它在任何普通属性中都是无效的,但JavaScript可能会读取它并对其进行操作。

第三部分:

如果属性包含一个或多个var()函数,并且这些函数在语法上是有效的,则必须假设整个属性的语法在解析时是有效的。它只在var()函数被替换之后,在计算值时进行语法检查。

这意味着在计算声明之前,上面看到的240,240,240值直接被替换到rgba()函数中。所以这个:

#element {
  background-color: rgba(var(--color), 0.8);
}

这似乎不是一个有效的CSS,因为rgba()期望不少于四个逗号分隔的数值,变成这样:

#element {
  background-color: rgba(240, 240, 240, 0.8);
}

当然,这是完全有效的CSS。

更进一步,你可以将alpha组件存储在它自己的自定义属性中:

:root {
  --color: 240, 240, 240;
  --alpha: 0.8;
}

代入,得到同样的结果:

#element {
  background-color: rgba(var(--color), var(--alpha));
}

这允许你有不同的alpha值,你可以在飞行中交换。


1好吧,如果你在一个不支持自定义属性的浏览器中运行代码片段,那么它就是。