我正在设计一个电子应用程序,所以我可以访问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>

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

其他回答

你可以使用线性渐变来改变颜色:

background: linear-gradient(to bottom, var(--your-color) -1000%, var(--mixin-color), 1000%)

$(() => { const setOpacity = () => { $('#canvas').css('--opacity', $('#opacity-value').val()) } const setColor = () => { $('#canvas').css('--color', $('#color-value').val()); } $('#opacity-value').on('input', setOpacity); $('#color-value').on('input', setColor); setOpacity(); setColor(); }) #canvas { width: 100px; height: 100px; border: 2px solid #000; --hack: 10000%; background: linear-gradient( to bottom, var(--color) calc((var(--opacity) - 1) * var(--hack)), transparent calc(var(--opacity) * var(--hack))); } #container { background-image: linear-gradient(45deg, #b0b0b0 25%, transparent 25%), linear-gradient(-45deg, #b0b0b0 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #b0b0b0 75%), linear-gradient(-45deg, transparent 75%, #b0b0b0 75%); background-size: 20px 20px; background-position: 0 0, 0 10px, 10px -10px, -10px 0px; padding: 10px; display: inline-block; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="container"> <div id="canvas"></div> </div> <hr/> <input type="range" id="opacity-value" min="0" max="1" step="0.1" value="0.5" /> <input type="color" id="color-value" />

如果你像我一样喜欢十六进制颜色,还有另一个解决方案。 十六进制值是6位,之后是alpha值。 00是100%透明99是75%然后它用字母“a1-af”然后“b1-bf”以“ff”结尾,这是100%不透明。

:root {
--color: #F00;
}

#element {
background: var(--color)f6;
}

你不能获取一个现有的颜色值并应用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好吧,如果你在一个不支持自定义属性的浏览器中运行代码片段,那么它就是。

如果你使用暗和光模式,我使用这个样本。我更喜欢分开的颜色和rgb颜色变量分配。所以我每个循环使用两个。我意识到这个解决方案不是纯代码。如果你想干代码,你可以使用一个循环。

$colors-light: ( white: #fff, black: #0c0d0e, orange: #f48024, green: #5eba7d, blue: #0077cc, red: #d1383d, red-100: #e2474c, red-200: red, ); $colors-dark: ( black: #fff, white: #2d2d2d, orange: #dd7118, green: #5eba7d, blue: #0077cc, red: #aa1c21, red-100: #c9292e, red-200: red, ); @function hexToRGB($hex) { @return red($hex), green($hex), blue($hex); } @mixin generate_colors($colors) { // Colors @each $color, $value in $colors { @if str-slice(#{$value}, 1, 1) == "#" { --#{$color}: #{$value}; } @else { --#{$color}: var(--#{$value}); } } // RGB Colors @each $color, $value in $colors { @if str-slice(#{$value}, 1, 1) == "#" { --RGB_#{$color}: #{hexToRGB($value)}; } @else { --RGB_#{$color}: var(--RGB_#{$value}); } } } :root { @include generate_colors($colors-light); } [data-theme="dark"] { @include generate_colors($colors-dark); }

干燥的代码

@mixin generate_colors($colors) { //颜色,RGB颜色 @每个$color, $value在$colors { @if str-slice(#{$value}, 1,1) == "#" { ——#{$颜色}:#{$价值}; ——RGB_ #{$颜色}:# {hexToRGB(美元值)}; } @其他{ ——#{$颜色}:var(——#{$价值}); ——RGB_ #{$颜色}:var(——RGB_ #{$价值}); } } }

css输出

:root { --white: #fff; --RGB_white: 255, 255, 255; --black: #0c0d0e; --RGB_black: 12, 13, 14; --orange: #f48024; --RGB_orange: 244, 128, 36; --green: #5eba7d; --RGB_green: 94, 186, 125; --blue: #0077cc; --RGB_blue: 0, 119, 204; --red: #d1383d; --RGB_red: 209, 56, 61; --red-100: #e2474c; --RGB_red-100: 226, 71, 76; --red-200: var(--red); --RGB_red-200: var(--RGB_red); } [data-theme="dark"] { --black: #fff; --RGB_black: 255, 255, 255; --white: #2d2d2d; --RGB_white: 45, 45, 45; --orange: #dd7118; --RGB_orange: 221, 113, 24; --green: #5eba7d; --RGB_green: 94, 186, 125; --blue: #0077cc; --RGB_blue: 0, 119, 204; --red: #aa1c21; --RGB_red: 170, 28, 33; --red-100: #c9292e; --RGB_red-100: 201, 41, 46; --red-200: var(--red); --RGB_red-200: var(--RGB_red); } body { background-color: var(--white); } .colors { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-orient: horizontal; -webkit-box-direction: normal; -ms-flex-direction: row; flex-direction: row; -ms-flex-wrap: wrap; flex-wrap: wrap; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; -webkit-box-align: center; -ms-flex-align: center; align-items: center; margin: 50px 0 0 30px; } .box { width: 100px; height: 100px; margin-right: 5px; } .black { background-color: var(--black); } .white { background-color: var(--white); } .orange { background-color: var(--orange); } .green { background-color: var(--green); } .blue { background-color: var(--blue); } .red { background-color: var(--red); } .red-200 { background-color: var(--red-200); } .black-rgba { background-color: rgba(var(--RGB_black), 0.5); } .white-rgba { background-color: rgba(var(--RGB_white), 0.5); } .orange-rgba { background-color: rgba(var(--RGB_orange), 0.5); } .green-rgba { background-color: rgba(var(--RGB_green), 0.5); } .blue-rgba { background-color: rgba(var(--RGB_blue), 0.5); } .red-rgba { background-color: rgba(var(--RGB_red), 0.5); } .red-rgba-200 { background-color: rgba(var(--RGB_red-200), 0.5); } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link rel="stylesheet" href="style.css" /> </head> <body> <div> <input type="checkbox" id="dark-switch" name="theme" /> <label for="dark-switch">Dark / Light</label> </div> <div class="color-box"> <div class="colors"> <div class="box red-200"></div> <div class="box black"></div> <div class="box white"></div> <div class="box orange"></div> <div class="box green"></div> <div class="box blue"></div> <div class="box red"></div> </div> <br> <h1>RGBA</h1> <div class="colors"> <div class="box red-rgba-200"></div> <div class="box black-rgba"></div> <div class="box white-rgba"></div> <div class="box orange-rgba"></div> <div class="box green-rgba"></div> <div class="box blue-rgba"></div> <div class="box red-rgba"></div> </div> </div> <script> const dark_switch = document.getElementById("dark-switch"); dark_switch.addEventListener("change", (e) => { e.target.checked ? document.documentElement.setAttribute("data-theme", "dark") : document.documentElement.setAttribute("data-theme", "light"); }); </script> </body> </html>

第一次在这里发帖。

一个简单的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>

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