Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any possibilty using CSS-variables in SASS?

Tags:

css

sass

I have different twig-templates that are supposed to be rendered with different colors. The styling via SASS is the same for each template exept for the color theme. This is why I want to set a CSS variable in each template. I though about a SASS variable that looks like something like this:

$pim-color: var(--color-primary);

I've already tried something like the following aswell:

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

$prim-color: color(primary);

But that seems to just return a string which doesn't work in my CSS.

Do you have any ideas how I could solve this? Kind regards, Phil.

like image 769
philman Avatar asked Oct 20 '25 13:10

philman


1 Answers

Basically in SASS you cannot store the complete variables string (css-name + css-value) to a var. But you can store the name of the css variable and use the SASS the variable to build/write the css variable.

Note: in this case you have to setup your colors seperate in css-variables/css-code. Now you can use the SASS variable to write the css variable.

Basic example:


//### SASS

$var-color-primary: --color-primary;

:root {
    #{$var-color-primary}: red;
}

.class {
    color: var($var-color-primary);
}



//###> compiles to css

:root {
  --color-primary: red;
}

.class {
  color: var(--color-primary);
}


Preparing an additional SASS map and SASS function as you thought about in your question you are able to to it more comfortable:


//### SASS

// setup your colors in a map
$css-color-vars: (
    primary: red,
    secondary: blue,
);

// automatic write colors of map to css variables using a SASS loop
:root {
    @each $color_name, $color in $css-color-vars{
        --color-#{$color-name}: #{$color};      
    }
}

// create function to easy access to css variables
@function css-color-var( $color ){
    @return var(--color-#{$color});
}

// use function to advice css variables 
.class {
    color: css-color-var( primary );
}


//###> compiles to css
:root {
  --color-primary: red;
  --color-secondary: blue;
}

.class {
  color: var(--color-primary);
}


like image 73
Brebber Avatar answered Oct 23 '25 07:10

Brebber