我正在使用 SCSS 创建网格布局——特别是 SCSS 中的 @for
指令。
同样重要的是要注意,我在 CSS 转义的帮助下在我的标记中使用数字类。
这是我的 SCSS:
$columns: 12;
$column: 100% / $columns;
@for $i from 1 through $columns {
@if $i == 10 {
$i: 1 0;
} @else if $i == 11 {
$i: 1 1;
} @else if $i == 12 {
$i: 1 2;
}
.row .\3#{$i} .columns {
width: $column * $columns;
}
}
这编译成以下内容:
.row .\31 .columns {
width: 100%;
}
.row .\32 .columns {
width: 100%;
}
.row .\33 .columns {
width: 100%;
}
.row .\34 .columns {
width: 100%;
}
.row .\35 .columns {
width: 100%;
}
.row .\36 .columns {
width: 100%;
}
.row .\37 .columns {
width: 100%;
}
.row .\38 .columns {
width: 100%;
}
.row .\39 .columns {
width: 100%;
}
.row .\31 0 .columns {
width: 100%;
}
.row .\31 1 .columns {
width: 100%;
}
.row .\31 2 .columns {
width: 100%;
}
我的问题是类 .10
、.11
和 .12
。由于我在第一个数字后添加了带有 @if
的所需空间(通常需要使用 css 转义符),因此我现在需要删除第二个数字后的第二个空格。这在 Sass/SCSS 中可行吗?
因此,如果这如我所愿,那么单个数字类将像这样编写:
.row .\31 .columns { width: 100%; }
多个数字类可以这样写:
.row .\31 2.columns { width: 100%; }
我知道 css 在编译时不是特别有效。我在答案中真正寻求的是 SCSS 什么是可能的,什么是不可能的。
最佳答案
您基本上想要的是始终在数字的第一位数字之后引入一个空格。因此,如果它是 1
,您需要 1_
,如果它是 11
,您需要 1_1
。
以下代码段将帮助您实现这一目标。都来自Advances Sass list functions by Hugo Giraudel ,所以一定要检查一下。
在列表的索引 n
处插入值
@function insert-nth($list, $index, $value) {
$result: null;
@if type-of($index) != number {
@warn "$index: #{quote($index)} is not a number for `insert-nth`.";
}
@else if $index < 1 {
@warn "List index 0 must be a non-zero integer for `insert-nth`";
}
@else if $index > length($list) {
@warn "List index is #{$index} but list is only #{length($list)} item long for `insert-nth'.";
}
@else {
$result: ();
@for $i from 1 through length($list) {
@if $i == $index {
$result: append($result, $value);
}
$result: append($result, nth($list, $i));
}
}
@return $result;
}
用法:
$list: a, b, d, e, f;
/* I want to add "c" as the 3rd index in the list */
$new-list: insert-nth($list, 3, c); // a, b, c, d, e, f
将列表转换为字符串
@function to-string($list, $glue: '', $is-nested: false) {
$result: null;
@for $i from 1 through length($list) {
$e: nth($list, $i);
@if type-of($e) == list {
$result: $result#{to-string($e, $glue, true)};
}
@else {
$result: if($i != length($list) or $is-nested, $result#{$e}#{$glue}, $result#{$e});
}
}
@return $result;
}
用法
$list: a, b, c d e, f, g, h;
$new-list: to-string($list); // abcdefgh
$new-list: to-string($list, '-'); // a-b-c-d-e-f-g-h
因此,对于您的问题,请使用 insert-nth
在列表的第二个位置插入一个空格,并使用空字符串作为分隔符将列表转换为字符串。然后将此字符串插入您的选择器。
关于html - 创建 .grid.column 类时的@for 指令问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45660376/