@if规则@if <expression> { ... }编写,它控制是否评估其块(包括以CSS形式发出任何样式)。表达式通常返回 true 或 false — 如果表达式返回 true,则计算块,如果表达式返回 false,则不计算。
SCSS
@mixin avatar($size, $circle: false) {
width: $size;
height: $size;
@if $circle {
border-radius: $size / 2;
}
}
.square-av { @include avatar(100px, $circle: false); }
.circle-av { @include avatar(100px, $circle: true); }编译为 CSS 结果:
CSS
.square-av {
width: 100px;
height: 100px;
}
.circle-av {
width: 100px;
height: 100px;
border-radius: 50px;
}@else
可以选择@if规则后跟@else规则,@else { ... } 编写。
语法:@else { ... }
SCSS
$light-background: #f2ece4;
$light-text: #036;
$dark-background: #6b717f;
$dark-text: #d2e1dd;
@mixin theme-colors($light-theme: true) {
@if $light-theme {
background-color: $light-background;
color: $light-text;
} @else {
background-color: $dark-background;
color: $dark-text;
}
}
.banner {
@include theme-colors($light-theme: true);
body.dark & {
@include theme-colors($light-theme: false);
}
}编译为 CSS 结果:
CSS
.banner {
background-color: #f2ece4;
color: #036;
}
body.dark .banner {
background-color: #6b717f;
color: #d2e1dd;
}@else if
语法:@else if <expression> { ... }。
SCSS
@mixin triangle($size, $color, $direction) {
height: 0;
width: 0;
border-color: transparent;
border-style: solid;
border-width: $size / 2;
@if $direction == up {
border-bottom-color: $color;
} @else if $direction == right {
border-left-color: $color;
} @else if $direction == down {
border-top-color: $color;
} @else if $direction == left {
border-right-color: $color;
} @else {
@error "Unknown direction #{$direction}.";
}
}
.next {
@include triangle(5px, black, right);
}编译为 CSS 结果:
CSS
.next {
height: 0;
width: 0;
border-color: transparent;
border-style: solid;
border-width: 2.5px;
border-left-color: black;
}true & false
任何地方true或者false是允许的,可以使用其它值。值false和null是falsey,其他所有值都被认为是ture。
例如,如果要检查字符串是否包含空格,则只需编写即可string.index($string, " ")。如果找不到字符串,则 返回该string.index()函数null,否则返回数字。
空字符串,空列表和数字
0在Sass中都是true。
自学教程
分享笔记