我使用以下算法在SASS中创建列类:
$columns: 8;
$exclude-columns: 5 7;
@for $i from 1 through $columns {
@for $j from 1 through $i {
$width: (100% / $i) * $j;
@if $i != $j and index($exclude-columns, $i) {
.layout-unit-#{$j}of#{$i} {
width: $width;
}
}
}
}
它工作正常,但输出有很多重复:
.layout-unit-1of2 { width: 50%; }
.layout-unit-1of3 { width: 33.33333%; }
.layout-unit-2of3 { width: 66.66667%; }
.layout-unit-1of4 { width: 25%; }
.layout-unit-2of4 { width: 50%; }
.layout-unit-3of4 { width: 75%; }
.layout-unit-1of6 { width: 16.66667%; }
.layout-unit-2of6 { width: 33.33333%; }
.layout-unit-3of6 { width: 50%; }
.layout-unit-4of6 { width: 66.66667%; }
.layout-unit-5of6 { width: 83.33333%; }
.layout-unit-1of8 { width: 12.5%; }
.layout-unit-2of8 { width: 25%; }
.layout-unit-3of8 { width: 37.5%; }
.layout-unit-4of8 { width: 50%; }
.layout-unit-5of8 { width: 62.5%; }
.layout-unit-6of8 { width: 75%; }
.layout-unit-7of8 { width: 87.5%; }
有没有办法让输出更像这样:
.layout-unit-1of2,
.layout-unit-2of4,
.layout-unit-3of6,
.layout-unit-4of8 { width: 50%; }
.layout-unit-1of3,
.layout-unit-2of6 { width: 33.33333%; }
.layout-unit-2of3,
.layout-unit-4of6 { width: 66.66667%; }
.layout-unit-1of4,
.layout-unit-2of8 { width: 25%; }
.layout-unit-3of4,
.layout-unit-6of8 { width: 75%; }
.layout-unit-1of6 { width: 16.66667%; }
.layout-unit-5of6 { width: 83.33333%; }
.layout-unit-1of8 { width: 12.5%; }
.layout-unit-3of8 { width: 37.5%; }
.layout-unit-5of8 { width: 62.5%; }
.layout-unit-7of8 { width: 87.5%; }
或者这是SASS的限制吗?
答案 0 :(得分:2)
这不是Sass的限制,而是算法。
这是一个至少需要 Sass 3.3 (see live demo on SassMeister)的解决方案:
注意:我修复了您的代码以支持排除列。
$columns: 8;
$exclude-columns: 5 7;
// A stack to store the different widths.
$width_stack: ();
@for $i from 1 through $columns {
@for $j from 1 through $i {
@if $i != $j and not index($exclude-columns, $i) {
$width: (100% / $i) * $j;
// Compute the number 66.66667% to a valid CSS selector: "66-66667".
$width_unitless: $width / 1% + unquote("");
$width_dot: str-index($width_unitless, '.');
@if $width_dot {
$width_unitless: str-slice($width_unitless, 0, $width_dot - 1) +
"-" +
str-slice($width_unitless, $width_dot + 1);
}
// Manage the stack of known widths to avoid repeats.
@if not index($width_stack, $width_unitless) {
$width_stack: append($width_stack, $width_unitless);
// Dynamic placeholder!
%mycols-#{$width_unitless} {
width: $width;
}
}
.layout-unit-#{$j}of#{$i} {
@extend %mycols-#{$width_unitless};
}
}
}
}