SCSS語法 - Control Directives & Expressions
一、Control directive
以下要點不打算多做說明,只列出scss語法與結果
1、@if
scss輸入
p { @if 1 + 1 == 2 { border: 1px solid; } @if 5 < 3 { border: 2px dotted; } @if null { border: 3px double; } }
css輸出
p { border: 1px solid; }
2、@else if
scss輸入
$type: monster;p {
@if $type == ocean {
color: blue;
}
@else if $type == matador {
color: red;
}
@else if $type == monster {
color: green;
}
@else {
color: black;
}
}
css輸出
p { color: green; }
3、@for
scss輸入
$squareCount: 3;@for $i from 1 through $squareCount {
#square-#{$i} {
background-color: red;
width: 50px * $i;
height: 120px / $i
}
}
css輸出
#square-1 { background-color: red; width: 50px; height: 120px; }#square-2 {
background-color: red;
width: 100px;
height: 60px;
}#square-3 {
background-color: red;
width: 150px;
height: 40px;
}
throught跟to的差別在於計數次數只差1個
scss輸入
$squareCount: 3;@for $i from 1 to $squareCount {
#square-#{$i} {
background-color: red;
width: 50px * $i;
height: 120px / $i
}
}
css輸出
#square-1 { background-color: red; width: 50px; height: 120px; }#square-2 {
background-color: red;
width: 100px;
height: 60px;
}
4、@each
a、@each $var in <list or map>
scss輸入
@each $animal in puma, sea-slug, egret, salamander { .#{$animal}-icon { background-image: url('/images/#{$animal}.png'); } }
css輸出
.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");
}
以map為例子
scss輸入
@each $header, $size in (h1: 2em, h2: 1.5em, h3: 1.2em) { #{$header} { font-size: $size; } }
css輸出
h1 { font-size: 2em; }h2 {
font-size: 1.5em;
}h3 {
font-size: 1.2em;
}
b、Multiple Assignment
scss輸入
@each $animal, $color, $cursor in (puma, black, default), (sea-slug, blue, pointer), (egret, white, move) { .#{$animal}-icon { background-image: url('/images/#{$animal}.png'); border: 2px solid $color; cursor: $cursor; } }
css輸出
.puma-icon { background-image: url("/images/puma.png"); border: 2px solid black; cursor: default; }.sea-slug-icon {
background-image: url("/images/sea-slug.png");
border: 2px solid blue;
cursor: pointer;
}.egret-icon {
background-image: url("/images/egret.png");
border: 2px solid white;
cursor: move;
}
5、@while
scss輸入
$i: 6;@while $i > 0 {
.item-#{$i} {
width: 2em * $i;
}
$i: $i - 2;
}
css輸出
.item-6 { width: 12em; }.item-4 {
width: 8em;
}.item-2 {
width: 4em;
}