Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 459
Vikhyath Maiya Avatar asked Oct 20 '25 20:10

Vikhyath Maiya


2 Answers

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

like image 69
Quentin Veron Avatar answered Oct 23 '25 13:10

Quentin Veron


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>
like image 28
miir Avatar answered Oct 23 '25 13:10

miir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!