5

So I have been trying to use CSS variables in HSLA. I need to keep the same color, but just change the opacity.

<div>
// content here
</div>

SCSS

:root {
  --color: 332, 61%, 78%;
}

div {
  background: hsla(var(--color), 0.5);
}

https://codepen.io/sammiepls/pen/zLpvXY

So I thought I would be able to just keep the hsl color in there and change the opacity on hover or whatnot by using the variable. It works, if I'm just using plain CSS. But I am using SCSS and it's causing it to fail because SASS has it's own HSL function that's expecting three values; the error I get is basically not enough arguments. Has anyone gotten a way around it? I tried using string interpolation #{} around the whole function but it didn't work.

sammiepls
  • 1,340
  • 2
  • 13
  • 19

2 Answers2

3

Hey I think what your want to do in SCSS is to treat the whole function as a string. This should work background: #{hsla(var(--color), 0.5)} that would output on CSS as background: hsla(var(--color), 0.5);

bruhbruh
  • 313
  • 1
  • 14
1

It does work! (now)

Here's your exact code running in the StackOverflow web snippet editor.

:root {
  --color: 332, 61%, 78%;
}

body {
  background: hsla(var(--color), 0.5);
}

It probably didn't work for you before because you were using LibSass (deprecated), the old transpiler. But if you use Dart Sass, you'll be just fine.

Note for Hugo: Hugo has a hard time installing Dart Sass, so it uses LibSass by default. You can see your exact issue in some of the Hugo issue threads.

Merchako
  • 789
  • 1
  • 8
  • 19
  • As far as I can tell, this only works now if the variable is defined in the **same file**. If it is defined in another file or component, then SCSS doesn't detect the variable and still produces the original error. – Brett Mar 07 '23 at 02:06
  • Even if you `@use`/`@include`/`@import` the other file, [@Brett](https://stackoverflow.com/users/1513557/brett)? – Merchako Apr 05 '23 at 15:05
  • I didn't try with `@use`/`@include`/`@import`, I suppose then SCSS would have knowledge of it. If the files are added to the web components separately (e.g. using a bundler) then SCSS doesn't know about it and it still doesn't work. – Brett Apr 05 '23 at 19:32