运算


运算 (Number Operations)

SassScript 支持 +, -, *, /, %,<, >, <=, >=,==, != 等运算,如果有必要会在不同单位间转换值。

p {
  width: 1in + 8pt;  ## in为英寸单位
}

编译为

p {
  width: 1.111in; }


除法运算 / (Division and /)

/ 在 CSS 中通常起到分隔数字的用途,SassScript 作为 CSS 语言的拓展也支持这个功能,同时也赋予了 / 除法运算的功能。

以下三种情况 / 将被视为除法运算符号:

  • 如果值,或值的一部分,是变量或者函数的返回值
  • 如果值被圆括号包裹
  • 如果值是算数表达式的一部分
p {
  font: 10px/8px;             // 纯CSS,无运算
  $width: 1000px;
  width: $width/2;            // 使用变量做除法
  width: round(1.5)/2;        // 使用函数做除法
  height: (500px/2);          // 使用括号进行除尘
  margin-left: 5px + 8px/2px; // 使用加、除
}

编译为

p {
  font: 10px/8px;
  width: 500px;
  height: 250px;
  margin-left: 9px;
}


如果需要使用变量,同时又要确保 / 不做除法运算而是完整地编译到 CSS 文件中,只需要用 #{} 插值语句将变量包裹。

p {
  $font-size: 12px;
  $line-height: 30px;
  font: #{$font-size}/#{$line-height};
}

编译为

p {
  font: 12px/30px;
}


颜色值运算 (Color Operations)

颜色值的运算是分段计算进行的,即分别计算红、绿色、蓝色的值:

p {
  color: #010203 + #040506;
}

计算 01 + 04 = 05 02 + 05 = 07 03 + 06 = 09,然后编译为

p {
  color: #050709;
}


使用 color functions 比计算颜色值更方便一些。

数字与颜色值之间也可以进行算数运算,同样也是分段计算的,比如

p {
  color: #010203 * 2;
}

计算 01 * 2 = 02 02 * 2 = 04 03 * 2 = 06,然后编译为

p {
  color: #020406;
}


需要注意的是,如果颜色值包含 alpha channel(rgba 或 hsla 两种颜色值),必须拥有相等的 alpha 值才能进行运算,因为算术运算不会作用于 alpha 值。

p {
  color: rgba(255, 0, 0, 0.75) + rgba(0, 255, 0, 0.75);
}

编译为

p {
  color: rgba(255, 255, 0, 0.75);
}


颜色值的 alpha channel 可以通过 opacify 或 transparentize 两个函数进行调整。

$translucent-red: rgba(255, 0, 0, 0.5);
p {
  color: opacify($translucent-red, 0.3); // 使用颜色增加指定不透明度
  background-color: transparentize($translucent-red, 0.25);  // 使颜色增加指定透明度
}

编译为

p {
  color: rgba(255, 0, 0, 0.8);
  background-color: rgba(255, 0, 0, 0.25);  
}


字符串运算 (String Operations)

+ 可用于连接字符串

p {
  cursor: e + -resize;
}

编译为

p {
  cursor: e-resize; }


如果引号字符串连接无引号字符串,运算结果是有引号的;

如果无引号字符串连接有引号字符串,运算结果则没有引号;

p:before {
  content: "Foo " + Bar;
  font-family: sans- + "serif";
}

编译为

p:before {
  content: "Foo Bar";
  font-family: sans-serif;
}


运算表达式与其他值连用时,用空格做连接符:

p {
  margin: 3px + 4px auto;
}

编译为

p {
  margin: 7px auto;
}


在有引号的文本字符串中使用 #{} 插值语句可以添加动态的值:

p:before {
  content: "I ate #{5 + 10} pies!";
}

编译为

p:before {
  content: "I ate 15 pies!";
}


空值被视作插入了空字符串:

$value: null;
p:before {
  content: "I ate #{$value} pies!";
}

编译为

p:before {
  content: "I ate pies!"; }


布尔运算 (Boolean Operations)

SassScript 支持布尔型的 and or 以及 not 运算。


数组运算 (List Operations)

数组不支持任何运算方式,只能使用 list functions 控制。


举报

© 著作权归作者所有


0