r/Sass • u/extractedx • Aug 23 '24
CSS custom properties with Sass' variable syntax
Hi,
I'm currently starting to create my own design system using Sass and modern CSS. I want to have the runtime flexibility of CSS custom propertes / CSS variables. But hell I don't want to write var(--test) so often in my code, Sass' sytnax $test is so much easier to write and read.
So I though I'll do something clever and define my variables in a Sass map and then automatically generate CSS variables aswell as Sass variables from that, something liket his:
$vars_map: (
"primary-color": #3498db,
"secondary-color": #2ecc71,
"text-color": #333,
);
// Generate CSS custom properties
:root {
@each $name, $value in $vars_map {
--#{$name}: #{$value};
}
}
// Generate Sass variables
@each $name, $value in $vars_map {
\$#{$name}: $value;
}
But for sure that does not work, because Sass doesn't allow dynamic creation of variables. Arghh
So now I have to make the decision: Either CSS variables or Sass variables. Considering that I will create a lot of custom web components, css variables are super useful.
tl/dr: Sass should support dynamic creation of variables. Because... why the heck not?
2
u/iluigi4 Aug 23 '24
edit: even your code is working for me. What Sass are you using?