@if 和 @else
,它控制其块是否被评估(包括发出任何样式作为 CSS)。表达式通常返回true或者false。如果表达式返回true,则计算块,如果表达式返回false,则不计算。
| scss 语句 | css 语句 |
|---|---|
@mixin |
.square-av {
width: 100px;
height: 100px;
}
.circle-av {
width: 100px;
height: 100px;
border-radius: 50px;
}
|
@else
一个。如果false,则计算该规则的块。
| scss 语句 | css 语句 |
|---|---|
$light-background: #f2ece4;
$light-text: #036;
$dark-background: #6b717f;
$dark-text: #d2e1dd;
@mixin theme-colors($light-theme: true) {
|
.banner {
background-color: #f2ece4;
color: #036;
}
body.dark .banner {
background-color: #6b717f;
color: #d2e1dd;
}
|
@else if
您还可以通过编写,来选择是否计算规则的块。如果这样做,则仅当前面的false,而true时,才会计算块。
实际上,您可以在true的第一个块,而不计算其他块。如果在链的末端有一个普通的@else,那么如果每个其他块都失败,则将对其块进行评估。
| scss 语句 | css 语句 |
|---|---|
@use "sass:math";
@mixin triangle($size, $color, $direction) {
height: 0;
width: 0;
border-color: transparent;
border-style: solid;
border-width: math.div($size, 2);
|
.next {
height: 0;
width: 0;
border-color: transparent;
border-style: solid;
border-width: 2.5px;
border-left-color: black;
}
|
真与假
在允许任何地方true或false的地方,您也可以使用其他值。false和null的值是 falsey,这意味着 Sass 认为它们表示错误并导致条件失败。其他所有值都被认为是真实的,因此 Sass 认为它们的工作方式类似true并导致条件成功。
例如,如果要检查字符串是否包含空格,则只需编写string.index($string," ").如果未找到该字符串,则该null,否则返回一个数字。
⚠️注意!
一些语言认为更多的值是虚假的,而不仅仅是false和null。Sass 不是其中一种语言!空字符串、空列表和数字0,在 Sass 中,都是真值。
