Kristoffer Lund Kristoffer Lund - 8 months ago 71
Sass (Sass) Question

Toggle scss variable file

I am trying to make a toggle between night mode and day mode only by changing colors. I have some base color variables inside my

_colors.scss
, and they are used all over my site. I use React to toggle a className between 'night-mode' and 'day-mode' at the first div of the project.

I have tried to wrap the variables in the mentioned class names, but the result is that no other files can access the variables. Therefore I was hoping for a solution where I can use a night-mode file and a day-time file and toggle between them.

As I see it now, the issue is that I can't wrap the $variables or the @import in a class name, which makes it difficult to know what mode is selected. I am looking for a solution that does not include jQuery (I have a variable globally stored that can be used for javascript reference if that ends up to be the best solution).

Answer Source

You can't toggle scss files at runtime, since they are already compiled to css.

I would go with CSS custom properties (sometimes called CSS variables) instead of pure Sass variables.

Example:

:root {
  --background: lightblue;
}


.night-mode {
  --background: darkblue;
}

.component {
  background-color: var(--background);
}

Toggle the class .night-mode on with javascript depending on the time of day.

You may of course feed your CSS custom properties from Sass variables in your scss files:

$bg-day: lightblue;
$bg-night: darkblue;

:root {
  --background: $bg-day;
}

.night-mode {
  -- background: $bg-night;
}

.component {
  background-color: var(--background);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download