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

标签 html sass

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/

相关文章:

css - Angular 6 Material 检索 Material 颜色

javascript - 如何通过保留 URL 参数执行 Javascript 重定向 url

PHP 检查报告未使用的 CSS 选择器。它由 PHP 回显标签使用

课后的 CSS sibling

css - 如何对 Sass for 循环的索引进行零填充?

css - compass : generate Sprites, 加上 Sprite 中每个图像的宽度/高度

css - 如何在不重复自己的情况下共享 CSS 子类

c# - 在特定位置动态添加按钮

javascript - 如何更改 Twitter 关注按钮的宽度?

javascript - 单击时使元素成为其父列表的第一个子元素