How to make a SCSS function that receives a CSS variable and converts it to SCSS variable then returns it
I want to make a function that gets the CSS variable and then returns a newly created SCSS variable in the function;
The reason why I'm doing this is SASS functions don't accept CSS vars. Like darken and lighten...
for example
This is the sass
&--dropdown {
list-style: none;
position: absolute;
width: 25rem;
height: 15rem;
background-color: myOwnDarkenFunc(var(--color-primary));
And the result should be (Coming from the function):- $color-primary
The reason sass functions do not accept css custom properties/css variables is that sass is being transpiled to css and is therefore not accessible at runtime.
While sass variables and functions only exist at compile time, css custom properties exist at runtime. This is why you can change css custom properties via JavaScript.
As far as I know there is no general solution to your problem other than using sass functions and sass variables for values that are hard coded somewhere in your scss code and to use css variables only inside css statements and css functions like calc()
or translate()
.
Just looking at your code it seems you just want to use a sass function to make a color darker. In this case you could just use the css function hsl()
instead and pass custom properties into it. This way you can easily achieve a darkening effekt when changing the value for lightness:
scss
:root {
--color-primary-h: 120;
--color-primary-s: 100%;
--color-primary-l: 25%; // 100% => white, 50% => normal, less than 50% => darker, 0% => black
}
.menu { // some example wrapper element for testing
&--dropdown {
list-style: none;
position: absolute;
width: 25rem;
height: 15rem;
background-color: hsl(var(--color-primary-h),var(--color-primary-s),var(--color-primary-l));
}
}
You can test the above SCSS code with a list like this one:
HTML
<ul class="menu--dropdown">
<li>one</li>
<li>two</li>
<li>three</li>
</ul>