Any way to use CSS Variables in SASS functions?

sammiepls picture sammiepls · Aug 17, 2018 · Viewed 16.6k times · Source

I have defined a color in my root:

:root {
--purple: hsl(266, 35%, 70%);
}

And I'm trying to use it in a SASS function to give it transparency:

.purple {
  background: transparentize(#{"var(--primary-color)"}, 0.7)
}

Does anyone know of a way to get this to work? Or is it just not possible?

Answer

Keivan Sina picture Keivan Sina · Aug 17, 2018

Global variables can be defined outside of an element in a :root pseudo-class:

:root {
  --color-background: #FFFFFF;
}

you can define a function like this:

@function color($color-name) {
  @return var(--color-#{$color-name});
}

and call it into your sass:

body { 
  color: color(primary); 
}

compiled sass code is:

body { 
  color: var(--color-primary); 
}