DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> Sass教程
6.3 @for 循環:告別逐一書寫的樣式
編輯:Sass教程     

接觸過 Bootstrap 的人,應該都見過 .col1 到 .col12 這種規律排列的樣式。在純 CSS 中,這種東西只能一格一格手寫;而在 Sass 裡,一個 @for 循環就能搞定。

語法:

方式1:@for $i from 開始值 through 結束值
方式2:@for $i from 開始值 to 結束值

說明:

兩種寫法唯一的差異是:方式 1 包含結束值,方式 2 不包含結束值。開始值與結束值皆為正整數。

舉例 1:

@for $i from 1 through 3 {
  .item-#{$i} {
    width:(20px * $i);
  }
}

編譯後的 CSS:

.item-1 {
  width:20px;
}
.item-2 {
  width:40px;
}
.item-3 {
  width:60px;
}

分析:

若把 @for $i from 1 through 3 改成 @for $i from 1 to 3,則只會產生兩段:

.item-1 {
  width:20px;
}
.item-2 {
  width:40px;
}

舉例 2:

@for $i from 1 through 3 {
  .border-#{$i} {
    border:#{$i}px solid red;
  }
}

編譯後的 CSS:

.border-1 {
  border: 1px solid red;
}
.border-2 {
  border: 2px solid red;
}
.border-3 {
  border: 3px solid red;
}

分析:

這裡的關鍵是插值語法 #{}:它把變數值嵌進選擇器名稱或屬性值字串中。如果對插值用法還不熟,建議回去複習「Sass 插值」一節再回來。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved