2

How to concatenate string and variable to create a variable name that already exists in sass?

$size: "sm";

$button-sm: 1rem;
$buttom-md: 1.5rem;

body {
    font-size: $button-#{$size};
}

output

body {
  font-size: 1rem;
}
  • Does this answer your question? [Creating or referencing variables dynamically in Sass](https://stackoverflow.com/questions/8533432/creating-or-referencing-variables-dynamically-in-sass) – Justinas Apr 14 '21 at 11:57

1 Answers1

1

In short, No, unfortunately you cannot generate variables dynamically like that. You can only dynamically change the value of a CSS-property. A workaround that comes quite close to what you are trying to achieve might be something like this:

$size: "rm";
$button-font: 1;

body {
   font-size: $button-font#{$size};
}

Another option could be creating a mixin like this that gives you the power of selecting your custom font-size by passing another $size variable to the mixin.

$size: 2;
$sizes: 1rem 2rem 3rem;

@mixin button($index) {
  font-size: nth($sizes, $index);
}

body {
  @include button($size);
}

A thing that is possible tho is combinding CSS with SCSS variables.
If you choose to use this combination this is probably going to be your solution:

$size: sm;

:root {
  --button: 1em;
  --button-sm: 2rem;
  --buttom-md: 3rem;
}

body {
  font-size: var(--button - $size);
}
Behemoth
  • 5,389
  • 4
  • 16
  • 40