Creating or referencing variables dynamically in Sass

后端 未结 6 1852
臣服心动
臣服心动 2020-11-22 01:31

I\'m trying to use string interpolation on my variable to reference another variable:

// Set up variable and mixin
$         


        
6条回答
  •  深忆病人
    2020-11-22 01:45

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

提交回复
热议问题