Creating or referencing variables dynamically in Sass

Sass does not allow variables to be created or accessed dynamically. However, you can use lists for similar behavior.

scss:

$list: 20px 30px 40px;    
@mixin get-from-list($index) {
  width: nth($list, $index);
}

$item-number: 2;
#smth {
  @include get-from-list($item-number);
}

css generated:

#smth {
  width: 30px; 
}
  • http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#lists
  • http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#list-functions

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; }

Tags:

Variables

Sass