1 . if ( ) 三元运算符
三元运算符 : if ( expression , value1 , value2) 如果表达式 expression 为真 ,返回第一个值 ,如果表达式 expression 为假 ,返回第二个值 。
p{
color : if( 1 + 1 = 2 , green , yellow )
}
此时 color 的值为 green
2 . @ if
当 @ if 的表达式返回值不是 false 或者 null 时 ,条件成立 ,输出 {} 内的代码 。
p{
@if 1 + 1 == 2 { height : 1px }
@if 5 > 3 { width : 2px }
@if null { color : yellow }
}
// 执行后的代码
p{
height : 1px;
width : 2px;
}
3 . @ for
两种语法格式 :
@for $var from <start> through <end>或者@for $var from <start> to <end>区别在于through与to的含义:当使用through时,条件范围包含<start>与<end>的值,而使用to时条件范围只包含<start>的值不包含<end>的值。另外,$var可以是任何变量,比如$i;<start>和<end>必须是整数值。
@for $i from 1 through 3 {
.item-#{$i} { width: 2em * $i; }
}
// 相当于
.item-1 {
width: 2em; }
.item-2 {
width: 4em; }
.item-3 {
width: 6em; }
4 . @each
@each指令的格式是$var in <list>,$var可以是任何变量名,比如$length或者$name,而<list>是一连串的值,也就是值列表。
@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'); }
5 . @while
@while指令重复输出格式直到表达式返回结果为false。这样可以实现比@for更复杂的循环,只是很少会用到。
$i: 6;
@while $i > 0 {
.item-#{$i} { width: 2em * $i; }
$i: $i - 2;
}
// 结果为
.item-6 {
width: 12em; }
.item-4 {
width: 8em; }
.item-2 {
width: 4em; }