4

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.

2 Answers 2

6

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);
}


Sign up to request clarification or add additional context in comments.

Comments

2

get it as string


$pim-color: #{"var(--color-primary)"};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.