运算符

Sass 支持一些处理不同值的有用运算符。这些包括标准的数学运算符,如 +*,以及针对各种其他类型的运算符:

  • == and != are used to check if two values are the same.
  • +, -, *, /, and % have their usual mathematical meaning for numbers, with special behaviors for units that matches the use of units in scientific math.
  • <, <=, >, and >= check whether two numbers are greater or less than one another.
  • and, or, and not have the usual boolean behavior. Sass considers every value "true" except for false and null.
  • +, -, and / can be used to concatenate strings.

⚠️ Heads up!

在 Sass 早期历史中,它添加了对颜色的数学运算支持。这些运算分别作用于颜色的 RGB 通道,因此两种颜色相加会产生一种颜色,其红色通道是它们红色通道的和,依此类推。

这种行为并不是很有用,因为逐通道的 RGB 算术与人类感知颜色的方式并不太对应。添加了颜色函数,它们更加有用,并且颜色运算被弃用。它们在 LibSass 和 Ruby Sass 中仍然被支持,但会产生警告,强烈建议用户避免使用。

运算顺序运算顺序 permalink

Sass 有一个相当标准的运算顺序,从最紧密到最宽松:

  1. 一元运算符 not+-/
  2. */% 运算符
  3. +- 运算符
  4. >>=<<= 运算符
  5. ==!= 运算符
  6. and 运算符
  7. or 运算符
  8. = 运算符,当它可用时。
Playground

SCSS Syntax

@debug 1 + 2 * 3 == 1 + (2 * 3); // true
@debug true or false and false == true or (false and false); // true
Playground

Sass Syntax

@debug 1 + 2 * 3 == 1 + (2 * 3)  // true
@debug true or false and false == true or (false and false)  // true

括号括号 permalink

你可以使用括号显式控制运算顺序。括号内的运算总是在括号外的运算之前求值。括号甚至可以嵌套,在这种情况下,最内层的括号将首先求值。

Playground

SCSS Syntax

@debug (1 + 2) * 3; // 9
@debug ((1 + 2) * 3 + 4) * 5; // 65
Playground

Sass Syntax

@debug (1 + 2) * 3  // 9
@debug ((1 + 2) * 3 + 4) * 5  // 65

单个等号单个等号 permalink

Sass 支持一个特殊的 = 运算符,仅在函数参数中允许,它只是创建一个不带引号的字符串,其两个操作数用 = 分隔。这是为了向后兼容非常老的仅限 IE 的语法。

Playground

SCSS Syntax

.transparent-blue {
  filter: chroma(color=#0000ff);
}
Playground

Sass Syntax

.transparent-blue
  filter: chroma(color=#0000ff)

CSS Output

.transparent-blue {
  filter: chroma(color=#0000ff);
}