前言
本文主要記錄了Sass 條件語句、循環語句、自定義函數的基本用法。
條件語句
在Sass中可以使用
@if
、
@if-else
、
@if-else
來進行條件判斷,用法和JS相同。
$width: 200px;
p {
@if ($width == 200px) {
color: #cc6699;
} @else if ($width == 300px) {
color: #f97c00;
} @else {
color: #eb1c27;
}
}
編譯為
p {
color: #cc6699;
}
/*# sourceMappingURL=demo.css.map */
循環語句
在Sass中可以使用
@for
、
@while
、
@each
來進行循環操作。
@for
@for
的用法不同于JS,Sass中的for有兩種格式:
@for $i from n through m
@for $i from n through m
-
表示變量i 的範圍是[n, m],包含m。@for $i from n through m
@for $i from 1 through 3 {
.item-#{$i} { width: 200px + $i*10; }
}
編譯為
.item-1 {
width: 210px;
}
.item-2 {
width: 220px;
}
.item-3 {
width: 230px;
}
/*# sourceMappingURL=demo.css.map */
@for $i from n to m
@for $i from n to m
-
表示變量i 的範圍是[n, m),不包含m。@for $i from n to m
@for $i from 1 to 3 {
.item-#{$i} { width: 200px + $i*10; }
}
編譯為
.item-1 {
width: 210px;
}
.item-2 {
width: 220px;
}
/*# sourceMappingURL=demo.css.map */
@while
與其他控制指令一樣, @while 指令直到語句計算結果為false,它疊代地輸出嵌套樣式。 要注意的關鍵是,計數器變量需要在每次疊代時遞增/遞減。
@each
在@each中,定義一個變量,其中包含清單中每個項目的值。
@each用法:
@each $var in <list or map>
示例:
自定義函數
Sass 支援自定義函數,在Sass中可以使用
@function
編寫函數。
$grid-width: 40px;
$gutter-width: 10px;
@function grid-width($n) {
@return $n * $grid-width + $gutter-width;
}
#sidebar { width: grid-width(3); }
編譯為
#sidebar {
width: 130px;
}
/*# sourceMappingURL=demo.css.map */
可以傳遞若幹個全局變量給函數作為參數。