Mcanic
Mcanic

Reputation: 1393

Variable values based on class

Why can't I change a scss variable based on a class? I want the variable to be green when in class dark-mode.

Css:

$test: red;

@mixin darkTheme {
  $test: green;
}

.theme-dark {
  @include darkTheme();

  .test {
    background-color: $test;
  }
}

Html:

<body class="dark-mode">
  <div class="test">test</div>
</body>

How do I accomplish this? What I don't want is 2 variables.

Upvotes: 0

Views: 1325

Answers (1)

miir
miir

Reputation: 1926

This is because of Variable Scoping.

In Sass, all variables declared outside of a mixin or function will have a global scope and can be referenced in any Sass selector that uses the variable. (source)

This means that any variable value set inside of a mixin or function is only available within that mixin or function, even if the variable was previously set globally.


Switching between different sets of Sass variables

Partials

You could have a partial file for each theme, and import those under each theme's parent class.

_theme-dark.scss
$background-color: #000;
$text-color: #fff;
_theme-light.scss
$background-color: #fff;
$text-color: #000;
_themed-page.scss
body {
    background: $background-color;
    color: $text-color;
}
theme-styles.scss
.theme-dark {
    @import "theme-dark";
    @import "themed-page";
}

.theme-light {
    @import "theme-light";
    @import "themed-page";
}

Maps

Another option is to store the theme values in a map and have a utility function to retrieve the desired value. (source)

_theme-variables.scss
$theme: 'default';

$theme-values: ( 
    'background-color': ( 
        'default': #eee,
        'light': #fff,
        'dark': #000
    ),
    'text-color': ( 
        'default': #333,
        'light': #000,
        'dark': #fff
    )
);

@function theme-value($key) {
    $map: map-get($theme-values, $key);
    @return map-get($map, $theme);
}
_themed-page.scss
body {
    background: theme-value('background-color');
    color: theme-value('text-color');
}
theme-styles.scss
.theme-dark {
    $theme: 'dark';
    @import "themed-page";
}

.theme-light {
    $theme: 'light';
    @import "themed-page";
}

Upvotes: 4

Related Questions