Vikhyath Maiya
Vikhyath Maiya

Reputation: 3192

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.

Upvotes: 4

Views: 8297

Answers (2)

miir
miir

Reputation: 1926

Since SASS is compiled top-down, you may redefine the variables for each theme, and duplicate the common styles, which will be compiled to use the correct variable values.

_dark-theme.scss

// Variables for dark theme
$background-color: #333;
$color: #fff;

_light-theme.scss

// Variables for light theme
$background-color: #eee;
$text-color: #333;

_common-styles.scss

// Styles used across all themes, uses theme variables
body {
    background: $background-color;
    color: $text-color;
}

main.scss

.dark-theme {
    @import "dark-theme";
    @import "common-styles";
}

.light-theme {
    @import "light-theme";
    @import "common-styles";
}

Then use the desired theme class at the top level in your html.

<body class="dark-theme">
    ...
</body>

Upvotes: 4

Quentin
Quentin

Reputation: 3289

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

Upvotes: 6

Related Questions