Anthony Frehner
Posted on October 6, 2020
SASS treats CSS variables (also known as custom properties) in a special way, which means it's a little difficult to create CSS vars dynamically:
Sass parses custom property declarations differently than other property declarations. All tokens, including those that look like SassScript, are passed through to CSS as-is.
Which can cause problems, especially for my situation where I want to
- Keep the SASS variables around because they're used in a lot of existing code, but also
- Add CSS variables for new code
So here's how I've worked around this. It's not ideal, because it still duplicates the name of the SASS variable, but it works for my situation. 🤷
$primary-color: #30dbb4;
@mixin add-css-variable($name, $color) {
--#{$name}: $color;
}
:root {
// repeat as necessary for all your vars
@include add-css-variable('primary-color', $primary-color);
}
You can test this out in the wonderful SassMeister playground
💖 💪 🙅 🚩
Anthony Frehner
Posted on October 6, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.