6.3.3 Less的变量和运算符

6.3.3 Less的变量和运算符

正如我们在前面Less示例文件中见到的,Less源文件可以使用@关键字定义变量。

Less源文件支持各种加(+)、减(-)、乘(*)、除(/)等常见的运算符,也可使用圆括号来改变运算符的优先级。而且任何数字、颜色、长度单位、百分比及变量都可以参与运算。
例如如下Less源文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@normal-height : 25px;
@baseColor : #eee;
@width: 1px;
.a {
height: @normal-height;
background-color: @baseColor;
border: @width solid black;
}
.b {
height: @normal-height - 5px;
// 除法
background-color: @baseColor / 2;
border: @width + 1 solid black;
}
.c {
height: 2 * @normal-height;
// 加法
background-color: @baseColor + #111;
// 圆括号,乘法
border: (@width + 1) * 2 dotted black;
}

这里的代码会对颜色值、长度值进行了计算。使用lessc命令编译上面的Less源文件:

1
$ lessc var.less var.css

生成CSS代码如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.a {
height: 25px;
background-color: #eee;
border: 1px solid black;
}
.b {
height: 20px;
background-color: #777777;
border: 2px solid black;
}
.c {
height: 50px;
background-color: #ffffff;
border: 4px dotted black;
}

在线Less编译工具

在线 LESS CSS 编译器