Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating or referencing variables dynamically in Sass

Tags:

variables

sass

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?

like image 818
Krzysztof Romanowski Avatar asked Dec 16 '11 11:12

Krzysztof Romanowski


People also ask

How do you create a reference variable dynamically in Sass?

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.

Can you dynamically create variables?

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.

Can you change SCSS variable value dynamically?

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).


1 Answers

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; } 
like image 102
dibbledeedoo Avatar answered Dec 04 '22 18:12

dibbledeedoo