如何使用 Sass 动态创建许多相似的 CSS 类

2025-06-04

如何使用 Sass 动态创建许多相似的 CSS 类

最初发表在我的博客上。

假设您的 Web 应用程序中允许使用 5 种尺寸的图标,并且它们以 6 像素为增量:12、18、24、30 和 36。您的 Sass 文件可能有类似以下内容来处理此问题:

.Icon {
  &--size-12 {
    width: 12px;
    height: 12px;
    font-size: 12px;
  }

  &--size-18 {
    width: 18px;
    height: 18px;
    font-size: 18px;
  }

  &--size-24 {
    width: 24px;
    height: 24px;
    font-size: 24px;
  }

  &--size-30 {
    width: 30px;
    height: 30px;
    font-size: 30px;
  }

  &--size-36 {
    width: 36px;
    height: 36px;
    font-size: 36px;
  }
}
Enter fullscreen mode Exit fullscreen mode

这些看起来都很像,对吧?类名的格式都一样,而且每个类名都将widthheight、 和font-size设置为相同的值。如果我告诉你,在 Sass 中可以动态地为类名创建 CSS 块,你会相信吗?

好吧,相信我!这是真的!

您可以通过以下方式引入来@for实现此目的:

.Icon {
  @for $i from 1 through 5 {
    $base-size: 12;
    $increment: 6;
    $calculated-size: $base-size + ($i * $increment);

    &--size-#{$calculated-size} {
      width: #{$calculated-size}px;
      height: #{$calculated-size}px;
      font-size: #{$calculated-size}px;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

但是,如果没有偶数增量怎么办?您也可以像这样循环遍历数组:

$icon-sizes: 12, 16, 32, 48;

.Icon {
  @each $size in $icon-sizes {
    &--size-#{$size} {
      width: #{size}px;
      height: #{size}px;
      font-size: #{size}px;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

你知道我有一份新闻通讯吗?📬

如果您想在我发布新博客文章或发布重大项目公告时收到通知,请访问https://ashleemboyer.com/newsletter

文章来源:https://dev.to/ashleemboyer/how-to-dynamically-create-many-similar-css-classes-with-sass-1538
PREV
我知道你累了
NEXT
只需少量代码即可实现流畅的滚动到顶部按钮