Can you dynamically define variable names in SCSS?

510 views Asked by At

I'm trying to create a mixin that will take an ID and declare a bunch of variables with that ID prefix at the start of the variable names.

Something like this -

@mixin declareVars($id) {
  $#{$id}-background-color: null !default;
  $#{$id}-background-image: null !default;
  $#{$id}-background-size: null !default;
  $#{$id}-background-position-x: null !default;
  $#{$id}-background-position-y: null !default;
  $#{$id}-background-repeat: null !default;
  $#{$id}-color: null !default;
  $#{$id}-border-radius: null !default;
  $#{$id}-border-width: null !default;
  $#{$id}-border-color: null !default;
  $#{$id}-padding: null !default;
  $#{$id}-margin: null !default;
}

The above throws a syntax error.

Is this functionality achievable in SCSS?

1

There are 1 answers

0
Yaroslav Trach On

Variable interpolation does not work at all.

But you can use CSS variables:

@mixin defineVars($id) {
  --#{$id}-background-color: tomato;
  --#{$id}-background-image: null;
  --#{$id}-background-size: null;
  --#{$id}-background-position-x: null;
  --#{$id}-background-position-y: null;
  --#{$id}-background-repeat: null;
  --#{$id}-color: null;
  --#{$id}-border-radius: null;
  --#{$id}-border-width: null;
  --#{$id}-border-color: null;
  --#{$id}-padding: null;
  --#{$id}-margin: null;
}

:root {
  @include defineVars('some-id');
}

body {
  background-color: var(--some-id-background-color);
}

Output of SCSS block:

:root {
    --some-id-background-color: tomato;
    --some-id-background-image: null;
    --some-id-background-size: null;
    --some-id-background-position-x: null;
    --some-id-background-position-y: null;
    --some-id-background-repeat: null;
    --some-id-color: null;
    --some-id-border-radius: null;
    --some-id-border-width: null;
    --some-id-border-color: null;
    --some-id-padding: null;
    --some-id-margin: null;
}

body {
    background-color: var(--some-id-background-color);
}