Search code examples
csssassscss-mixins

Why can't I use variable inside @include in my Sass loop?


So let's say I have the following mixins:

@mixin type-h1 {
    font-size: 36px;
    font-weight: bold;
}
        
@mixin type-h2 {
    font-size: 28px;
    font-weight: bold;
}
        
@mixin type-h3 {
    font-size: 24px;
    font-weight: bold;
}

Now I created utility classes:

.type-h1 {
  @include type-h1;
}

.type-h2 {
  @include type-h2;
}

.type-h3 {
  @include type-h3;
}

All good so far. Now I would like to simplify my code and generate the utility classes using Sass loops. This is what I have:

$variable: 1, 2, 3;
@each $value in $variable {
  .type-h#{$value} {
    @include type-h$variable;
  }
}

Anyone has an idea why this loop doesn't work?


Solution

  • You can create map with variables:

    $vars: (1: 36px, 2: 28px, 3: 24px);
    

    Then combine mixins into one:

    @mixin types($value) {
      font-size: $value;
      font-weight: bold;
    }
    

    And finally you can generate your utilities by:

    @each $size, $value in $vars {
      .type-h#{$size} {
        @include types($value);
      }
    }
    

    Here is link to Codepen.io with example