I am currently using Angular5 with sass v1.3.2.
My goal is to dynamically change a color that is widely used in the scss files of my single page app without having to recompile new files.
This color is globally defined in my _variables.css
as:
$brand: #123123;
For instance, it is utilized like this:
h1 {
color: $brand;
}
Upon researching, I discovered that I can alter the color if CSS variables are used, for example:
# CSS
:root {
--brand: #123123
}
#JS
document.documentElement.style.setProperty('--brand', '#456456');
# OR
document.querySelector(':root').style.setProperty('--brand', '#456456');
But to achieve this using SCSS, I had to utilize the css-vars mixin as follows:
$brand: #123123;
:root {
@include css-vars((
--brand: #{$brand},
));
}
And then utilize it like so:
h1 {
color: var(--brand);
}
However, two issues arose:
- Even after these steps,
--brand
wasn't visible at root. In addition, the CSS generated in
<script type="text/css">
by angular-cli did not contain--brand
anywhere; instead, it compiled the CSS variable into#123123
, resulting in:h1 { color: #123123; }
Do you have any suggestions on how to successfully modify a global color at runtime? Or perhaps how to place my CSS within :root
and prevent SASS from compiling it?
UPDATE
As demonstrated by @JonUleis, using css-var
is unnecessary. Now, the variable --brand
appears in the DOM under :root
.
However, the line color: var(--brand);
still does not show up in the CSS, causing h1
to lack a color style entirely.
After updating node-sass
to version 4.9.0
from 4.8.3
, everything worked perfectly.