首页 > 技术文章 > 7:sass中的运算

bijiapo 2016-04-26 18:14 原文

sass中计算的使用

运算在程序中是最常见的,css3中只有calc()可以使用,进行计算
这是介绍calc的文章,刚兴趣的可以点击查看

sass中可以进行各种计算

注意:运算符两侧最好有空格

1:加法

加法运算可以在变量和属性中使用

属性中使用

sass

.box{
  width:20px+8in;
  height: 8in+20px;
  margin: 10px+10px;
}

css:

.box {
  width: 788px;
  height: 8.20833in;
  margin: 20px; }

变量中使用

sass

$width1:20px;
$width2:10px;
$width:$width1+$width2;
.box{
  width:$width;
}

css:

.box {
width: 30px; }

注意:

  • 必须是同一类型的单位,如果是不同类型,编译会报错
  • 同一类型的单位,后者会把类型转化为前者类型进行计算
  • 加号两侧可以有空格,也可以没有

2:减法

减法运算可以在变量和属性中使用

属性中使用

sass

$width:200px;
.box{
  width:$width - 1in;
}

css:

.box {
width: 104px; }

变量中使用

sass

$width1:20px;
$width2:10px;
$width:$width1 - $width2;
.box{
  width:$width;
}

css:

.box {
width: 10px; }

注意:

  • 必须是同一类型的单位,如果是不同类型,编译会报错
  • 同一类型的单位,后者会把类型转化为前者类型进行计算
  • 减号两侧须有空格

3:乘法

乘法运算可以在变量和属性中使用

属性中使用

sass

$width:20px;
.box{
  width:$width*2;
}

css:

.box {
width: 40px; }

变量中使用

sass

$width1:20px;
$width2:10;
$width:$width1*$width2;
$height1:20px;
$height:$height1*2;
.box{
  width:$width;
  height:$height;
}

css:

.box {
  width: 200px;
  height: 40px; }

注意:

  • 必须是同一类型的单位,如果是不同类型,编译会报错
  • 同一类型的单位,只能用一种,同时用多种编译会报错
  • 乘号俩侧可以有空格,也可以没有

4:除法

除法运算可以在变量和属性中使用

sass

$width:20px;
$margin:100px / 2;
$padding:100px;
.box{
  width:(100px / 2);
  height: 100px / 5 + 1in;
  margin: $margin;
  padding: $padding / 2;
  border:round(10) / 10;
}

css:

.box {
  width: 50px;
  height: 116px;
  margin: 50px;
  padding: 50px;
  border: 1; }

注意:

  • 必须是同一类型的单位,如果是不同类型,编译会报错
  • 同一类型的单位,只能用一种,同时用多种编译会报错
  • 由于“/”在sass中已经作为一种特殊符号使用,所以直接会使用“/”作为除号时候,将不会生效,
  • 需要用括号把表达式括起来,除号可以生效
  • 如果表达式中有其他运算,除号可以生效
  • 用变量进行除法运算,除号可以生效
  • 使用函数计算,除号可以生效
  • 除号俩侧可以有空格,也可以没有
  • 两个数相除,单位形同,结果单位没有了

5:变量计算

sass

$width1:200px;
$width2:20px;
.box{
  width:$width1 + $width2
}

css:

.box {
  width: 220px; }

6:数字计算

就是加减乘除等基本运算

7:颜色计算

分段运算,红蓝绿单独运算
sass:

.box{
  color:#010203 + #040506;
  background: #010203 * 2;
}

css:

.box {
  color: #050709;
  background: #020406; }

8:字符计算

通过加号对字符串进行连接

通过加号可以将字符连接

sass

$content:"Hello"+""+"sass";
.box:before{
  content:$content;
  cursor:e+ -resize
}

css:

.box:before {
  content: "Hellosass";
  cursor: e-resize; }

如果加号左侧是字符串,结果是一个字符串

如果加号左侧不是字符串,结果不是一个字符串

sass:

.box:before{
  content:"Foo " + bar;
  font-family:sans- + "self"
}

css:

.box:before {
  content: "Foo bar";
  font-family: sans-self; }

推荐阅读