SCSS 创建一个部分命名的泛型 class

SCSS create a partial named generic class

是否可以有一个像这样的 class 的部分

.theme-color- {
  &yellow {
    color: yellow
  }
  &red {
    color: red
  }
  &blue {
    color: blue
  }
}

但像这样的通用方式

$yellow = yellow;
$red = red;
$blue = blue;

.theme-color-#{$my-color} {
  color: #{$my-color};
}
<div class="theme-color-red"></div>

您可以使用 @each:

$colors: red, yellow, blue;

@each $color in $colors {
  .theme-color-#{$color} {
    color: $color;
  }
}

这会生成以下内容 CSS:

.theme-color-red {
  color: red;
}

.theme-color-yellow {
  color: yellow;
}

.theme-color-blue {
  color: blue;
}

如果您想指定自定义颜色值,您还可以将 @each 与地图一起使用而不是列表:

$colors: (red: '#ff0000', yellow: '#fffd62', blue: '#0000ff');

@each $color, $hex in $colors {
  .theme-color-#{$color} {
    color: $hex;
  }
}

结果如下 CSS:

.theme-color-red {
  color: "#ff0000";
}

.theme-color-yellow {
  color: "#fffd62";
}

.theme-color-blue {
  color: "#0000ff";
}