I'm trying to implement switchable themes for a project, it's a Mendix project, but let's suppose it's a website.
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:
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.
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?
CSS Variables to the Rescue CSS variables is a standard which enables you to have variables in CSS. SCSS is compiled to CSS during compile time, and SCSS variables are replaced with resolved value during compile time, which means there is no way to change the variable during run time.
Sass Set Color Functions An RGB color value is specified with: rgb(red, green, blue). Each parameter defines the intensity of that color and can be an integer between 0 and 255, or a percentage value (from 0% to 100%). Sets a color using the Red-Green-Blue-Alpha (RGBA) model.
CSS variables have access to the DOM, which means that you can change them with JavaScript.
A Sass variable must be initialized with a value. To change the value, we simply replace the old value with a new one. A variable that's initialized inside a selector can only be used within that selector's scope. A variable that's initialized outside a selector can be used anywhere in the document.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With