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

:root {
  --color: #f0f0f0;
}

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

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

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

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


当前回答

这在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>

其他回答

这在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>

我知道OP没有使用预处理器,但如果以下信息是这里答案的一部分,我会得到帮助(我还不能评论,否则我会评论@BoltClock答案。

如果你正在使用,例如scss,上面的答案将会失败,因为scss试图用特定于scss的rgba()/hsla()函数编译样式,这需要4个参数。然而,rgba()/hsla()也是css的原生函数,所以你可以使用字符串插值来绕过scss函数。

示例(在sass 3.5.0+中有效):

:根{ ——color_rgb: 250, 250, 250; ——color_hsl: 250, 50%, 50%; } div { /*这是有效的CSS,但在scss编译中将失败*/ Background-color: rgba(var(——color_rgb), 0.5); /*这是有效的scss,将生成*/上面的CSS background - color: # {' rgba (var(——color_rgb), 0.5)的}; } < div > < / div >

请注意,字符串插值对非CSS的scss函数(如lightight())不起作用,因为生成的代码不是函数式CSS。但它仍然是有效的scss,因此编译时不会收到错误。

第一次在这里发帖。

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

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

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);
}

如果你使用暗和光模式,我使用这个样本。我更喜欢分开的颜色和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>