【问题标题】:Why can't I use variable inside @include in my Sass loop?为什么我不能在我的 Sass 循环中的 @include 中使用变量?
【发布时间】:2022-01-26 10:43:34
【问题描述】:

假设我有以下混合:

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

现在我创建了实用程序类:

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

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

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

到目前为止一切顺利。现在我想简化我的代码并使用 Sass 循环生成实用程序类。这就是我所拥有的:

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

有人知道为什么这个循环不起作用吗?

【问题讨论】:

    标签: css sass scss-mixins


    【解决方案1】:

    您可以使用变量创建地图:

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

    然后将mixins合二为一:

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

    最后,您可以通过以下方式生成实用程序:

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

    Here is link to Codepen.io with example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 2012-06-29
      • 2021-02-07
      • 2012-03-30
      • 1970-01-01
      相关资源
      最近更新 更多