How to dynamically switch color themes using SASS?

12,436

You can't dynamically change sass variables in the browser. Here is a more detailed explanation:

Changing variables values scss

A possible solution for you is to add or remove a class to the body that represents the theme. Then, for example, if body has class "dark-theme", background color is black and so on.

Share:
12,436
Rumata
Author by

Rumata

Documentary film director, VFX compositor, interested in 3D graphics and programming. I have 5 dogs, all rescued from the street.

Updated on June 11, 2022

Comments

  • Rumata
    Rumata almost 2 years

    I'm trying to implement switchable themes for a project, it's a Mendix project, but let's suppose it's a website.

    • There are many different pages, and different elements on each page.
    • All styles for them are written in SASS. The pages and elements use values from one separate SASS file with variables - variables-1.
    • I have a second SASS file with the same variables but different values - variables-2.

    Problem:
    I need to change the color theme of the website on a button click. So basically I need all the elements to take colors from the different set of variables when I click a button.


    I see two options here:

    1. Compile 2 css files and switch between them: link all sass files to variables-1, compile CSS file, then link all sass files to variables-2, compile second css file. Switch between them on a button click.

      In this option, colors won't be assigned dynamically, and every time when I make changes I will have to manually link each sass file to different variables, or change variables values, and recompile everything. Also I won't be able to continue working on the project and switch themes at the same time.

    2. Predefine color themes in mixins, compile css classes for each theme like in this article, and use some custom js logic to assign corresponding classes to the elements.

      Most likely won't work, since there are too many elements in the project, and would be too complicated to change class for each one.

    How can I solve this problem?

  • Bato-Bair Tsyrenov
    Bato-Bair Tsyrenov over 4 years
    How to achieve that with sass?
  • Nico Diz
    Nico Diz over 4 years
    The first part of my answer has a link with that explanation. Regarding the second possibility, you can see an implementation here: jsfiddle.net/sm7a2qv8
  • Bato-Bair Tsyrenov
    Bato-Bair Tsyrenov over 4 years
    I meant more like the whole theming system: github.com/batousik/angular-bootswatch-dynamic-seed. Is there a way to make this kind of thing simpler? And @Rumata was this something you had in mind?
  • harsha reddy
    harsha reddy over 4 years
    IE browser wont support this