The built-in if() function allows you to branch on a condition and returns only one of two possible outcomes. It can be used in any script context. The if function only evaluates the argument corresponding to the one that it will return – this allows you to refer to variables that may not be defined or to have calculations that would otherwise cause an error (E.g. divide by zero).
当 的表达式返回值不是 false
或者 null
时,条件成立,输出 {}
内的代码:
编译为
p {
border: 1px solid; }
声明后面可以跟多个
@else if
声明,或者一个 声明。如果
@if
声明失败,Sass 将逐条执行 if
声明,如果全部失败,最后执行 @else
声明,例如:
$type: monster;
p {
@if $type == ocean {
color: blue;
} @else if $type == matador {
color: red;
} @else if $type == monster {
color: green;
} @else {
color: black;
}
}
p {
color: green; }
指令可以在限制的范围内重复输出格式,每次按要求(变量的值)对输出结果做出变动。这个指令包含两种格式:
@for $var from <start> through <end>
,或者 $var from <start> to <end>
,区别在于 through
与 to
的含义:当使用 through
时,条件范围包含 <start>
与 <end>
的值,而使用 时条件范围只包含 <start>
的值不包含 <end>
的值。另外,$var
可以是任何变量,比如 $i
;<start>
和 <end>
必须是整数值。
编译为
.item-1 {
.item-2 {
width: 4em; }
.item-3 {
width: 6em; }
@each
指令的格式是 $var in <list>
, $var
可以是任何变量名,比如 $length
或者 $name
,而 <list>
是一连串的值,也就是值列表。
将变量
$var
作用于值列表中的每一个项目,然后输出结果,例如:
@each $animal in puma, sea-slug, egret, salamander {
.#{$animal}-icon {
background-image: url('/images/#{$animal}.png');
}
}
.puma-icon {
background-image: url('/images/puma.png'); }
.sea-slug-icon {
background-image: url('/images/sea-slug.png'); }
.egret-icon {
background-image: url('/images/egret.png'); }
.salamander-icon {
background-image: url('/images/salamander.png'); }
8.4.1 Multiple Assignment
The @each directive can also use multiple variables, as in $var1, $var2, … in . If is a list of lists, each element of the sub-lists is assigned to the respective variable. For example:
is compiled to:
background-image: url('/images/puma.png');
border: 2px solid black;
cursor: default; }
.sea-slug-icon {
background-image: url('/images/sea-slug.png');
cursor: pointer; }
.egret-icon {
background-image: url('/images/egret.png');
border: 2px solid white;
cursor: move; }
Since maps are treated as lists of pairs, multiple assignment works with them as well. For example:
@each $header, $size in (h1: 2em, h2: 1.5em, h3: 1.2em) {
#{$header} {
font-size: $size;
}
}
is compiled to:
h1 {
font-size: 2em; }
h2 {
font-size: 1.5em; }
h3 {
font-size: 1.2em; }
.item-6 {
width: 12em; }
.item-4 {
width: 8em; }
.item-2 {