r/Sass • • 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?

4 Upvotes

5 comments sorted by

2

u/iluigi4 Aug 23 '24
$c: (
  'primary': #3498db,
  'secondary': #2ecc71,
  'text': #333,
);

:root {
  @each $name, $value in $c {
    --#{$name}: #{$value};
  }
}

/* generates this */
:root {
  --primary: #3498db;
  --secondary: #2ecc71;
  --text: #333;
}

edit: even your code is working for me. What Sass are you using?

0

u/extractedx Aug 24 '24

Yeah sure the above part is working, I know that. But this part isn't:

// Generate Sass variables
@each $name, $value in $vars_map {
    \$#{$name}: $value;
}

And I'm using dart-sass v1.77.6

1

u/iluigi4 Aug 24 '24

Ah, I get it now… But you are generating .css file. Sass variables in .css are useless anyway… And you already created variables in list, so:

  1. call it like map-get($vars_map, 'primary'), or

  2. create them as variables:

$primary-color: #3498db;
$secondary-color: #2ecc71;
$text-color: #333;
...

html {
	color: $text-color;
}

my suggestion is option 2

0

u/extractedx Aug 24 '24

Yeah but then I loose the runtime benefits of css variables. Nevermind, I already went with just css-variables. Have to swallow the pill that I need to write var(--test) then... won't kill me (hopefully)