[英]SCSS: How to combine @for with @each?
HTML HTML
<div class="row">
<div class="col">first</div>
<div class="col">second</div>
<div class="col">third</div>
</div>
SCSS SCSS
$statistics: ("first", "second", "third");
:root {
--first: red;
--second: blue;
--third: green;
}
.row {
@for $i from 1 through length($statistics) {
@each $variable in $statistics {
.col:nth-child(#{$i}) {
color: var(--#{$variable});
}
}
}
}
i want to compile it like我想编译它
.row {
.col:nth-child(1) {
color: var(--first);
}
.col:nth-child(2) {
color: var(--second);
}
.col:nth-child(3) {
color: var(--third);
}
}
Where am I wrong?我哪里错了? Each .col has all 3 colors.每个.col都有 3 个 colors。 I want each statistic to have only one color in order in $statistics.我希望每个统计数据在 $statistics 中只有一种颜色。 The first .col had the first, the second .col the second etc...第一个.col有第一个,第二个.col有第二个等等......
EDIT what if the variables are defined like this?编辑如果变量是这样定义的怎么办?
$statistics: (
"header": ("first", "second", "third")
);
Problem is that you have a first loop with @for
looping through all the values of $statistics
and then @each
doing the same which results in repeated values.问题是你有一个第一个循环, @for
循环遍历$statistics
的所有值,然后@each
执行相同的操作,这会导致重复值。 This should be done with a single loop.这应该用一个循环来完成。 I can think of two ways of achieving what you want:我可以想到两种实现您想要的方法:
.row {
@for $i from 1 through length($statistics) {
$variable: nth($statistics, $i);
.col:nth-child(#{$i}) {
color: var(--#{$variable});
}
}
}
or或者
.row {
@each $variable in $statistics {
$i: index($statistics, $variable);
.col:nth-child(#{$i}) {
color: var(--#{$variable});
}
}
}
In the case of the variable defined as:在变量定义为的情况下:
$statistics: (
"header": ("first", "second", "third")
);
You can use map-get
to obtain the variables.您可以使用map-get
来获取变量。 Something like:就像是:
$header: map-get($statistics, "header");
@each $variable in $header {
$i: index($header, $variable);
.col:nth-child(#{$i}) {
color: var(--#{$variable});
}
}
This is the same as before but looping with $header
instead of $statistics
这与以前相同,但使用$header
而不是$statistics
循环
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.