SCSS语法 – Control Directives & Expressions

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

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;
}