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

我正在使用 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...

这个工作得很好,但是 我接下来要做的是根据所选择的 $column 数量动态地生成一个长长的列类列表,这些列类用逗号分隔,例如,我想让它看起来像这样:

.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 语法有点困惑。

有人知道吗?

70112 次浏览

我想你可能想看看 @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;
}

@ 在文件中扩展。

还有一种方法可以做到你的问题特别要求的: 生成(并使用)一个用逗号分隔的类列表。 D. 亚历山大的回答完全适用于你的情况,但我发布了这个替代方案,以防有人看到这个问题的另一个用例。

这是一支正在演示的笔: http://codepen.io/davidtheclark/pen/cvrxq

基本上,您可以使用 顶嘴功能来实现您想要的结果。具体来说,我使用 append向列表中添加类(以逗号分隔) ,使用 unquote避免与类名中的句点发生编译冲突。

所以我的混音结果是这样的:

@mixin col-x {
$col-list: null;
@for $i from 1 through $columns {
.col-#{$i} {
width: $column-size * $i;
}
$col-list: append($col-list, unquote(".col-#{$i}"), comma);
}
#{$col-list} {
float: left;
}
}

Thnx to@davideclark 这里有一个更通用的版本:

@mixin attr-x($attr, $attr-count: 10, $attr-steps: 10, $unit: '%') {
$attr-list: null;
@for $i from 1 through $attr-count {
$attr-value: $attr-steps * $i;


.#{$attr}#{$attr-value} {
#{$attr}: #{$attr-value}#{$unit};
}


$attr-list: append($attr-list, unquote(".#{$attr}-#{$attr-value}"), comma);
}


#{$attr-list} {
//append style to all classes
}
}

像这样使用它:

@include attr-x('margin-left', 6, 5, 'px');
//or
@include attr-x('width');

结果是这样的:

.margin-left5 {
margin-left: 5px; }


.margin-left10 {
margin-left: 10px; }


...


.margin-left30 {
margin-left: 30px; }


.width10 {
width: 10%; }


.width20 {
width: 20%; }


...


.width100 {
width: 100%; }