5

Say you have the CSS custom property for a color:

--color: 255,0,0

And you want to mix it specially every time with rgb or rgba as the need requires. This is valid CSS:

rgba(var(--color), .3)

...but Sass explodes. I've been trying to see if I could write a mixin or something but I can't figure out how to get around Sass's insistence on using it's own color functions even when they are not necessary.

1
  • For added context I know it explicitly has to be three digits in the way the variable is defined. And I've tested this in vanilla CSS, it works. This appears to be a bug where Sass doesn't know how to deal with custom properties yet. Apr 27, 2017 at 23:00

4 Answers 4

6

Got it! This is a bit hacky but this allows you to create a custom function that utilizes the rgba() function with CSS custom properties (as allowed in the spec):

@function swatch($swatch-color, $swatch-alpha:1) {
  @return unquote("rgba(var(--#{$swatch-color}), #{$swatch-alpha})");
}
:root {
  --green: 0,255,0;
}
.green { color: swatch(green, .1); }

Found the key to the solution in a Sass bug report. This only works because the unquoting and interpolation bypass the default rgba() function.

3

Perhaps using interpolation rgba(#{--color}, .3)?

1
  • Comes back with an error of: Error: argument $color` of rgba($color, $alpha) must be a color` Apr 27, 2017 at 22:53
2

Another temporary workaround for this is to use RGB values only in your variables like you are already:

--color: 255, 255, 255;

Then if you use the RGB or RGBA function with capitals, SASS will ignore it and plain CSS is able to parse it. You can then adjust the opacity!

RGB(var(--color));
RGBA(var(--color), .3);
-1

rgba(var(--color), .3) is not valid:

div {
  width: 50px;
  height: 20px;
  outline: 1px dashed black;
}

:root {
  --color: red;
}

#correct {
  background: var(--color);
}

#incorrect {
  background: rgba(var(--color), .3);
}
<div id="correct"></div>
<div id="incorrect"></div>

2
  • --color: red; would make it invalid. Note how I'm using --color: 255,0,0;. Apr 27, 2017 at 22:50
  • This works in pure CSS: :root { --color: 255,0,0; } div { background-color: rgba(var(--color), .3); } Apr 27, 2017 at 22:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.