布尔值

布尔值是逻辑值 truefalse。除了它们的字面形式,布尔值还可以由相等关系运算符返回,以及许多内置函数,如 math.comparable()map.has-key()

Playground

SCSS Syntax

@use "sass:math";

@debug 1px == 2px; // false
@debug 1px == 1px; // true
@debug 10px < 3px; // false
@debug math.comparable(100px, 3in); // true
Playground

Sass Syntax

@use "sass:math"

@debug 1px == 2px  // false
@debug 1px == 1px  // true
@debug 10px < 3px  // false
@debug math.comparable(100px, 3in)  // true

你可以使用布尔运算符处理布尔值。and 运算符在两边都为 true 时返回 trueor 运算符在任一边true 时返回 truenot 运算符返回单个布尔值的相反值。

Playground

SCSS Syntax

@debug true and true; // true
@debug true and false; // false

@debug true or false; // true
@debug false or false; // false

@debug not true; // false
@debug not false; // true
Playground

Sass Syntax

@debug true and true  // true
@debug true and false  // false

@debug true or false  // true
@debug false or false  // false

@debug not true  // false
@debug not false  // true

使用布尔值使用布尔值 permalink

你可以使用布尔值来选择是否执行 Sass 中的各种操作。@if 规则在其参数为 true 时评估一块样式:

Playground

SCSS Syntax

@use "sass:math";

@mixin avatar($size, $circle: false) {
  width: $size;
  height: $size;

  @if $circle {
    border-radius: math.div($size, 2);
  }
}

.square-av {
  @include avatar(100px, $circle: false);
}
.circle-av {
  @include avatar(100px, $circle: true);
}
Playground

Sass Syntax

@use "sass:math"

@mixin avatar($size, $circle: false)
  width: $size
  height: $size

  @if $circle
    border-radius: math.div($size, 2)



.square-av
  @include avatar(100px, $circle: false)

.circle-av
  @include avatar(100px, $circle: true)

CSS Output

.square-av {
  width: 100px;
  height: 100px;
}

.circle-av {
  width: 100px;
  height: 100px;
  border-radius: 50px;
}







if() 函数在参数为 true 时返回一个值,在参数为 false 时返回另一个值:

Playground

SCSS Syntax

@debug if(true, 10px, 30px); // 10px
@debug if(false, 10px, 30px); // 30px
Playground

Sass Syntax

@debug if(true, 10px, 30px)  // 10px
@debug if(false, 10px, 30px)  // 30px

Truthiness and FalsinessTruthiness and Falsiness permalink

Anywhere true or false are allowed, you can use other values as well. The values false and null are falsey, which means Sass considers them to indicate falsehood and cause conditions to fail. Every other value is considered truthy, so Sass considers them to work like true and cause conditions to succeed.

For example, if you want to check if a string contains a space, you can just write string.index($string, " "). The string.index() function returns null if the string isn’t found and a number otherwise.

⚠️ Heads up!

Some languages consider more values falsey than just false and null. Sass isn’t one of those languages! Empty strings, empty lists, and the number 0 are all truthy in Sass.