Skip to content

Sass 計次迴圈 @for:through 與 to 的差別

Sass 計次迴圈 @for 的用法

@for 依照一段 連續的數字 重複執行。當你要的不是一組現成的資料、而是「一到十二」這種序列時,它比 @each 合適。

through 與 to

scss
@for $i from 1 through 3 {
  .col-#{$i} { width: $i * 100px; }
}
css
.col-1 { width: 100px; }
.col-2 { width: 200px; }
.col-3 { width: 300px; }
scss
@for $i from 1 to 3 {
  .col-#{$i} { width: $i * 100px; }
}
css
.col-1 { width: 100px; }
.col-2 { width: 200px; }
關鍵字含不含結尾1 到 12 會跑幾次
through12 次
to不含11 次

柵格少一欄,八成是寫成 to

through 是實務上比較常用的那個。記法:t-h-r-o-u-g-h 比較長,範圍也比較長。

遞減

起始值比結束值大就會往下數:

scss
@for $i from 5 through 1 {
  .layer-#{$i} { z-index: $i * 10; }
}
css
.layer-5 { z-index: 50; }
.layer-4 { z-index: 40; }
/* ... */
.layer-1 { z-index: 10; }

起訖必須是整數

scss
@for $i from 1 through 3.5 { }    // ❌ Error
@for $i from 0px through 100px { } // ❌ Error

要小數或帶單位的刻度,就讓計數維持整數,在區塊裡再換算:

scss
@for $i from 1 through 8 {
  .space-#{$i} { margin: $i * 4px; }   // 4px ~ 32px
}

十二欄柵格

@for 的經典用途:

scss
@use "sass:math";

$columns: 12;

@for $i from 1 through $columns {
  .col-#{$i} {
    width: math.percentage(math.div($i, $columns));
  }
}
css
.col-1 { width: 8.3333333333%; }
.col-2 { width: 16.6666666667%; }
/* ... */
.col-12 { width: 100%; }

Grid 的話更簡潔:

scss
@for $i from 1 through 12 {
  .span-#{$i} { grid-column: span $i; }
}

完整做法見 柵格與間距系統

依序延遲的動畫

scss
@for $i from 1 through 6 {
  .item:nth-child(#{$i}) {
    animation-delay: $i * 0.08s;
  }
}

一行迴圈換來六條錯開的延遲,轉場與動畫 的清單進場效果常這樣寫。

該用 @for 還是 @each

情況
一到十二欄的柵格@for
一組具名的主題色@each
依序延遲的 nth-child@for
斷點、間距等有名字的刻度@each

別用 @for 加索引去讀 list

scss
// ⚠️ 囉嗦又容易錯
@for $i from 1 through list.length($colors) {
  $c: list.nth($colors, $i);
}

// ✅
@each $c in $colors { }

list 的索引從 1 開始,用 @for 手動走訪很容易差一格。

常見問題

through 和 to 差在哪?

through 包含結尾的數字,to 不包含。從 1 到 12 的柵格要用 through,跑 12 次;用 to 只會跑 11 次,最後一欄就會不見。

@for 可以遞減嗎?

可以,起始值寫得比結束值大就會自動遞減。常用在產生層級遞減的 z-index,或是由外而內的堆疊順序。

計數變數可以不是整數嗎?

不行,起訖值必須是不帶單位的整數。需要小數或帶單位的刻度時,讓計數維持整數,在區塊內部再乘上單位或係數。

什麼時候該用 @each 而不是 @for?

當你要處理的是一組具名的資料而不是連續數字時。用 @for 搭配索引去 list 裡取值不但囉嗦,還容易因為索引從 1 開始而算錯。

延伸閱讀