Skip to main content
  1. Posts/

【SCSS】@eachで配列のインデックスを使う

·101 words·1 min
Scss
  1. @each の代わりに配列と@for を使う

@each の代わりに配列と@for を使う
#

やりたいこととしては、@each の中で現在の要素が何番目を取得することです。
調べた限りだと@each 内で現在の要素の添字を取得することはできなさそうでしたが、stackoverflowに実現方法が載っていました。

配列、@for、nth()関数を使うとうまいこといきます。
このブログで実際に使っている scss が以下のようになります。

// 以下$themesという配列を作る
$theme1: #184d47;
$theme2: #96bb7c;
$theme3: #d6efc7;
$theme4: #e8f0e3;
$themes: $theme1, $theme2, $theme3, $theme4;

// @eachの代わりに配列$themesの添字を@forで取得し、
// nth()と添字を使って現在の要素を取得する
@for $i from 1 through length($themes) {
  $t: nth($themes, $i); // $tに現在の要素が格納される
  .theme#{$i} {
    color: $t;
  }
  .bg--theme#{$i} {
    background-color: $t;
  }
}

↑ をコンパイルした結果が以下のようになります。

.theme1 {
  color: #184d47;
}
.bg--theme1 {
  background-color: #184d47;
}
.theme2 {
  color: #96bb7c;
}
.bg--theme2 {
  background-color: #96bb7c;
}
.theme3 {
  color: #d6efc7;
}
.bg--theme3 {
  background-color: #d6efc7;
}
.theme4 {
  color: #e8f0e3 #fad586;
}
.bg--theme4 {
  background-color: #e8f0e3 #fad586;
}