I'm trying to use string interpolation on my variable to reference another variable:
// Set up variable and mixin $foo-baz: 20px; @mixin do-this($bar) { width: $foo-#{$bar}; } // Use mixin by passing 'baz' string as a param for use $foo-baz variable in the mixin @include do-this('baz');
But when I do this, I get the following error:
Undefined variable: "$foo-".
Does Sass support PHP-style variable variables?
To make a dynamic variable is not possible in SASS as of now, since you will be adding/connecting another var that needs to be parsed once when you run the sass command. As soon as the command runs, it will throw an error for Invalid CSS, since all your declared variables will follow hoisting.
Use an Array of VariablesThe simplest JavaScript method to create the dynamic variables is to create an array. In JavaScript, we can define the dynamic array without defining its length and use it as Map. We can map the value with the key using an array and also access the value using a key.
SCSS is compiled to CSS during compile time, and SCSS variables are replaced with resolved value during compile time, which means there is no way to change the variable during run time. However, CSS variables just sits there during run time, and you can dynamically CRUD them during run time with JavaScript (Web API).
This is actually possible to do using SASS maps instead of variables. Here is a quick example:
Referencing dynamically:
$colors: ( blue: #007dc6, blue-hover: #3da1e0 ); @mixin colorSet($colorName) { color: map-get($colors, $colorName); &:hover { color: map-get($colors, #{$colorName}-hover); } } a { @include colorSet(blue); }
Outputs as:
a { color:#007dc6 } a:hover { color:#3da1e0 }
Creating dynamically:
@function addColorSet($colorName, $colorValue, $colorHoverValue: null) { $colorHoverValue: if($colorHoverValue == null, darken( $colorValue, 10% ), $colorHoverValue); $colors: map-merge($colors, ( $colorName: $colorValue, #{$colorName}-hover: $colorHoverValue )); @return $colors; } @each $color in blue, red { @if not map-has-key($colors, $color) { $colors: addColorSet($color, $color); } a { &.#{$color} { @include colorSet($color); } } }
Outputs as:
a.blue { color: #007dc6; } a.blue:hover { color: #3da1e0; } a.red { color: red; } a.red:hover { color: #cc0000; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With