How to control Sass Variable with javascript
I have a Sass file which is generating a CSS file. I have used many variables in my sass file for background color, font-size, now I want to control my all variables through JavaScript.
For example, in style.sass we have
$bg : #000;
$font-size: 12px;
How can I change these values from JavaScript?
You can't. SASS is a CSS preprocessor, which means that all SASS specific information disapears when you compile it to CSS.
CSS
:root {
subTitleLeftMargin: 1.5vw;
}
.element {
margin-left: var(--subTitleLeftMargin);
}
JS or TS
document.documentElement.style.setProperty("--subTitleLeftMargin", "6vw");
I also needed this functionality, here's what worked for me:
With JS you can set a class to body, ex. .blue
or .default
Now create a set of rules to extend from, which you'd like to set:
.default .themeColor {
color: 'red';
}
.blue .themeColor {
color: 'blue';
}
Now instead of having color: $someColor
in your scss file, use it like this:
.someClass {
@extend .themeColor;
}
Now, if your body will have the default
class, the color inside someClass
will be red, and if body will have the blue
class the color will be blue.