gpt4 book ai didi

html - SCSS : How to combine @for with @each?

转载 作者:行者123 更新时间:2023-12-04 10:08:37 29 4
gpt4 key购买 nike

HTML

<div class="row">
<div class="col">first</div>
<div class="col">second</div>
<div class="col">third</div>
</div>

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});
}
}
}
}

我想像 一样编译它
.row {
.col:nth-child(1) {
color: var(--first);
}
.col:nth-child(2) {
color: var(--second);
}
.col:nth-child(3) {
color: var(--third);
}
}

我哪里错了?每个 .col 有所有 3 种颜色。我希望每个统计信息在 $statistics 中按顺序只有一种颜色。第一 .col 有了第一个,第二个 .col 第二个等等...

编辑
如果变量是这样定义的怎么办?
$statistics: (
"header": ("first", "second", "third")
);

最佳答案

问题是你的第一个循环是 @for循环遍历 $statistics 的所有值然后 @each做同样的事情会导致重复的值。这应该通过一个循环来完成。我可以想到两种实现你想要的方法:

.row {
@for $i from 1 through length($statistics) {
$variable: nth($statistics, $i);

.col:nth-child(#{$i}) {
color: var(--#{$variable});
}
}
}

或者
.row {
@each $variable in $statistics {
$i: index($statistics, $variable);
.col:nth-child(#{$i}) {
color: var(--#{$variable});
}
}
}

在变量定义为的情况下:
$statistics: (
"header": ("first", "second", "third")
);

您可以使用 map-get来获取变量。就像是:
$header: map-get($statistics, "header");

@each $variable in $header {
$i: index($header, $variable);

.col:nth-child(#{$i}) {
color: var(--#{$variable});
}
}

这与之前相同,但循环使用 $header而不是 $statistics

关于html - SCSS : How to combine @for with @each?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61447880/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com