0

What I have?

An scss file with pre-defined colors, which are css variables saved as hex color codes (e.g. --error-color: #B42318;).

I now want to use this --error-color variable within an rgba function (because I want to use it in a linear-gradient). E.g. like this: rgba(var(--error-color), 1)). Unfortunately, this doesn't seem to work.

What I've noticed:

When I use the following HTML:

<div class="box color1">1</div>
<div class="box color2">2</div>
<div class="box color3">3</div>
<div class="box color4">4</div>
<div class="box color5">5</div>

With the following SCSS file:

.box {
  width: 50px;
  height: 50px;
  --color-as-rgb: 180,35,24;
  --color-as-hex: #B42318;
}

.color1 { background-color: var(--color-as-hex); }
.color2 { background-color: rgba(#B42318, 1); }
.color3 { background-color: rgba(180,35,24, 1); }
.color4 { background-color: rgba(var(--color-as-hex), 1); }
.color5 { background-color: rgba(var(--color-as-rgb), 1); }

Only #4, which is exactly what I want in my case, doesn't work as intended..

enter image description here

Is there a way to convert a hexadecimal color to a comma-separated RGB during compilation of the scss? Or any kind of alternative so I can use my existing hexadecimal css variables with an opacity?

Two things I've tried (without success):

Convert the css variable to a scss variable, and try to use that in the rgba, which will have a similar result as #4.

.color6 {
  $color-as-hex: var(--color-as-hex);
  background-color: rgba($color-as-hex, 1);
}

Use transparentize instead of rgba, but it seems to be even more limited and actually gives scss compilation errors:

.color7a { background-color: transparentize(#B42318, 0); } /* Works hard-coded without css variable */
.color7b { background-color: transparentize(180,35,24, 0); } /* SassError: Only 2 arguments allowed, but 4 were passed. */
.color7c { background-color: transparentize(var(--color-as-hex), 0); } /* SassError: $color: var(--color-as-hex) is not a color. */
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135

0 Answers0