Using CSS Variables as Sass function arguments

Majka picture Majka · Aug 4, 2017 · Viewed 8.4k times · Source

Is there a way to use CSS variables with Sass functions e.g. lighten? Something like this:

:root {
  --color: #ff00ff;
}

.div {
  background-color: lighten(var(--color), 32%);
}

I'm getting an error message that "Argument $color of lighten($color, $amount) must be a color".

I'm using CSS (not Sass) variables, because I need to use them in js.

Answer

Jordan Whitfield picture Jordan Whitfield · Dec 18, 2017

UPDATE:

I just read that Sass 3.5.0 now should support CSS Custom Properties with native CSS functions. I tried this with node-sass but as yet libsass doesn't support this feature of Ruby Sass 3.5


For native CSS functions I think sass replaces them with its own implementation, as I had to use string interpolation in Sass to get my css to compile:

--Primary: #{"hsl(var(--P-h), var(--P-s), var(--P-l))"};

For Sass functions, the closest thing I came up with pure CSS for lightness (won't work with IE, obviously), is to separate the colour values into hue, saturation and lightness to use inside hsl(). This could also be used with rgba(), but hsl() can be used to control shades more easily for the theme of the application:

:root {
    --P-h: 203;
    --P-s: 82%;
    --P-l: 41%;
    --Primary: hsl(var(--P-h), var(--P-s), var(--P-l));
}

Then the shades for active, hover, accents etc. can use an altered lightness by using calc to calculate a percentage of the original lightness:

:root {
    --Primary-20: hsl(var(--P-h), var(--P-s), calc(var(--P-l) * 0.8));
}

This could go the other way to lighten also, but this won't work for every scenario. It's also pretty messy and you end up with a bit of pollution in the variable scope.