csssass

Convert rgb to rgba using scss and assign to css property


I need to convert from rgb to rgba using scss' rgba function, and assign the result to a css property (for use with a style library outside my control).

Both these approaches fail:

.test1 { --foo: rgba(#f00, .5); }    // .test1 { --foo: rgba(#f00, .5) }
$col: rgba(#f00, .5);
.test2 { --foo: $col; }              // .test2 { --foo: $col }

How does one do this?


Solution

  • You need to use #{} (string interpolation) to ensure SCSS properly outputs the evaluated RGBA value inside the CSS variable:

    .test1 { --foo: #{rgba(#f00, 0.5)}; }
    

    Alternative with Variables If you need to define the color first:

    $col: rgba(#f00, 0.5);
    .test2 { --foo: #{$col}; }
    

    output:

    .test1 { --foo: rgba(255, 0, 0, 0.5); }
    .test2 { --foo: rgba(255, 0, 0, 0.5); }