Reputation: 287
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});
}
}
}
}
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. I want each statistic to have only one color in order in $statistics. The first .col had the first, the second .col the second etc ...
EDIT what if the variables are defined like this?
$statistics: (
"header": ("first", "second", "third")
);
Upvotes: 2
Views: 761
Reputation: 2720
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. 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. 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
Upvotes: 2