Search code examples
csssassmixins

Sass - import variables to be used in mixin


Is there a way to import external variables into mixins?
I would like to generate a variablename from a mixin argument
and then call it from an external source. Does this make any sense?


variables.scss

/* Striped status bar variables ******************************************/

$greyFirstGradientStartColor: #999999;
$greyFirstGradientEndColor: #d3cfcf;
$greySecondGradientStartColor: #ababab;
$greySecondGradientEndColor: #595959;

mixins.scss

@import variables.scss

[...]

@mixin gradient-repeating($color, $deg, $firstWidth, $space, $secondWidth){

  background-image:
    repeating-linear-gradient(
      $deg,
      $(#{$color}FirstGradientStartColor),
      $(#{$color}FirstGradientEndColor) $firstWidth+px,
      $(#{$color}SecondGradientStartColor) ($firstWidth+$space)+px,
      $(#{$color}SecondGradientStartColor) $secondWidth+px
  );
}

my-main-css-file.scss

@import variables.scss;  
@import mixins.scss;  

[...]

@include gradient-repeating(grey, -45, 20, 0, 20);  

Solution

  • No. Variable variables do not exist in Sass. Lists or lists of lists are typically used instead.

    Your mixin could be written like this:

    $grey-gradient: #999999 #d3cfcf, #ababab #595959;
    
    @mixin gradient-repeating($color, $deg, $firstWidth, $space, $secondWidth){
        $firstColor: nth($color, 1);
        $secondColor: nth($color, 2);
        background-image:
            repeating-linear-gradient(
              $deg,
              nth($firstColor, 1),
              nth($firstColor, 2) $firstWidth+px,
              nth($secondColor, 1) ($firstWidth+$space)+px,
              nth($secondColor, 1) $secondWidth+px
            );
    }
    
    .foo {
        @include gradient-repeating($grey-gradient, -45, 20, 0, 20);
    }