Search code examples
angularsasscss-variablesscss-mixins

Scss Variable based on class


I am trying to do theming for one of my projects and i was using css variables for the same. I was defining css variable as follows

.theme-1 {
    --var-1: #ffe;
    --var-2: #000;
}

.theme-2 {
    --var-1: #fff;
    --var-2: #000;
}

and in the html i was applying the theme as follows

<div [ngClass]="'theme-1'">
<!--content>

<-->
</div>

Everything works great except that css-variables are not supported till IE -11 as mentioned Here.

Question

Is there any way to achieve this with scss variables so that i can define global variables and change the value based on class .

Note: I am using angular for my project, hence i have to worry about view encapsulation as well. It would be great if the answer can be achieved with default encapsulation.

Thanks in advance.


Solution

  • I personally prefer using a function for that, but you could make it with a mixin too.

    Create a Map with properties bind to as many values as themes you have.
    Then, define a custom property for fetching this map and return the wanted value.

    $theme: (
      color: (#000, #FFF),
      border: (dashed, solid),
      // etc.
    );
    
    @function theme($property, $index) {
      @return nth(map-get($theme, $property), $index);
    }
    
    .light.foo {
      color: theme(color, 1);
    }
    
    .dark.foo {
      color: theme(color, 2);
    }
    

    Demo SassMeister