css - 如何动态生成用逗号分隔的类列表?

标签 css sass

我正在使用 SASS 的 SCSS 语法来创建动态网格系统,但遇到了障碍。

我正在尝试使网格系统像这样完全动态:

$columns: 12;

然后我像这样创建列:

@mixin col-x {
  @for $i from 1 through $columns {
  .col-#{$i} { width: $column-size * $i; }
  }
}

哪些输出:

.col-1 {
    width: 4.16667%;
  }

.col-2 {
    width: 8.33333%;
}
etc...

这很好用,但是我接下来要做的是根据所选的 $columns 数量动态生成一长串用逗号分隔的列类 - 例如,我希望它看起来像这样:

.col-1,
.col-2,
.col-3,
.col-4,
 etc... {
float: left;
}

我已经厌倦了这个:

@mixin col-x-list {
  @for $i from 1 through $columns - 1 {
  .col-#{$i}-m { float: left; }
  }
}

但是输出是这样的:

.col-1 {
  float: left;
}
.col-2 {
  float: left;
}
etc...

我对这里的逻辑以及创建这样的东西所需的 SCSS 语法有点困惑。

有没有人有什么想法?

最佳答案

我想你可能想看看@extend。如果您将其设置为:

$columns: 12;

%float-styles {
  float: left;
}

@mixin col-x-list {
  @for $i from 1 through $columns {
      .col-#{$i}-m { @extend %float-styles; }
  }
}

@include col-x-list;

它应该在您的 css 文件中呈现为:

.col-1-m, .col-2-m, .col-3-m, .col-4-m, .col-5-m, .col-6-m, .col-7-m, .col-8-m, .col-9-m, .col-10-m, .col-11-m, .col-12-m {
  float: left;
}

@extend in the docs .

关于css - 如何动态生成用逗号分隔的类列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19087811/

相关文章:

Laravel Blade、Mix 和 SASS 资源版本共享

ruby-on-rails - 从 Rails 4 中的 Controller 操作设置 Sass 变量

css - 执行休息;在 SCSS 中

html - 如何让我的网站背景变成渐变色?

css - 滚动图像

jquery - 4 col 在 Bootstrap 中滚动 一个一个滚动

css - 使用css将圆分成24段

css - 带有@for的sass数组?

html - 使用最少的 CSS 代码实现

sass - 我的 WebCompiler 扩展使用哪个版本的 SASS?