Sass控制指令
三元运算符
/* if(expression, value1, value2) */
p {
color: if(1+1==2, green, yellow);
}
div {
color: if(1+1==3, green, yellow);
}
/**
p {
color: green;
}
div {
color: yellow;
}
*/
分支
单分支
单分支使用@if:
p {
@if 1+1 == 2 {
color: red;
}
margin: 10px;
}
div {
@if 1+1 == 3 {
color: red;
}
margin: 10px;
}
/**
p {
color: red;
margin: 10px;
}
div {
margin: 10px;
}
*/
双分支
双分支使用@if和@else:
p {
@if 1+1 == 2 {
color: red;
} @else {
color: blue;
}
margin: 10px;
}
div {
@if 1+1 == 3 {
color: red;
} @else {
color: blue;
}
margin: 10px;
}
/**
p {
color: red;
margin: 10px;
}
div {
color: blue;
margin: 10px;
}
*/
多分支
使用@else if来写多分支:
$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
for循环的语法如下:
/* 包含 end */
@for $var from <start> through <end>
/* 不包含 end */
@for $var from <start> to <end>
示例如下:
@for $i from 1 to 3{
.item-#{$i} {
width: $i * 2em;
}
}
@for $i from 1 through 3{
.item2-#{$i} {
width: $i * 2em;
}
}
/**
.item-1 {
width: 2em;
}
.item-2 {
width: 4em;
}
.item2-1 {
width: 2em;
}
.item2-2 {
width: 4em;
}
.item2-3 {
width: 6em;
}
*/
while
语法如下:
@while expression
示例如下:
$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;
}
*/
一定要要在while里面书写改变变量的表达式,否则就会形成一个死循环。
each
类似于JS里面的for...of循环,会把数组或者字典类型的每一项值挨着取出来。
@each $var in $vars
var可以是任意的变量名,但是vars只能是list或者maps。
- list.scss
- map.scss
$arr:puma, sea-slug, egret, salamander;
/* 遍历列表 */
@each $animal in $arr {
.#{$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");
}
*/
$dict: (
h1: 2em,
h2: 1.5em,
h3: 1.2em,
h4: 1em,
);
/* 遍历字典 */
@each $header, $size in $dict {
#{$header}{
font-size: $size;
}
}
/**
h1 {
font-size: 2em;
}
h2 {
font-size: 1.5em;
}
h3 {
font-size: 1.2em;
}
h4 {
font-size: 1em;
}
*/