less 简介

简介

Less 是一种由Alexis Sellier设计的动态层叠样式表语言。受Sass所影响,同时也影响了Sass的新语法:Scss。现在流行的CSS预处理器有Sass、Less和Stylus。详细介绍
Less 是开源的,其第一个版本由Ruby 写成,但在后续的版本当中,Ruby 逐渐被替换为JavaScript。
简单的来说,LESS就是在网页设计的时候,可以更方便地编写CSS的工具。官网描述是这样的:Less 使用动态行为(如变量、混合、运算、函数)拓展CSS。它有很多优点比如说:减少代码量、良好的模块化思想等等。当然你也可以用更加强大的Sass 和 Compass。 SASS 和 LESS 的介绍与比较

Less 运行环境

受益于JavaScript,LESS可以在客户端上运行(IE6+、Webkit、Firefox),也可以在服务端运行(Node.js、Rhino)。
使用Node.js 库时,首先要全局安装less

1
npm install -g less

接下来就可以使用lessc来编译.less文件了:

1
lessc style.less

也可以编译到另一个css 文件

1
lessc style.less style.csss

也可以用GUI编译工具 Koala

Less 语法

  • 注释

Less 中支持两种注释类似于其他编程语言的单行注释和多行注释 ,但功能不同

1
2
// 该注释不会编译到css 文件中
/* 该注释会编译到css 文件中 */

编译后的css 文件为

1
/* 该注释会编译到css 文件中 */
  • 变量

Less中的变量充许你在样式中的某个地方对常用的值进行定义,然后应用到样式中。这样只要改变你定义的变量参数值就可以达到改变全局的效果,你也可以对变量进行运算操作。

1
2
3
4
5
6
7
8
9
@color: #4d926f;

.header {
color: @color;
}

h2 {
color: @color - 10;
}
1
2
3
4
5
6
7
.header {
color: #4d926f;
}

h2 {
color: #438865;
}
  • 混合(Mixins)

混合可以在一个类中直接调用另一个类,即嵌套。而被嵌入的类也称为是一个变量

1
2
3
4
5
6
7
8
9
10
.box {
width: 50px;
height: 50px;
background: #4d926f;
}

.header {
.box;
border: 1px solid gray;
}

编译后的css

1
2
3
4
5
6
7
8
9
10
11
12
13
.box {
width: 50px;
height: 50px;
background: #4d926f;
}

.header {
background: #4d926f;
width: 50px;
height: 50px;
color: #4d926f;
border: 1px solid gray;
}

混合也可以带参数,即函数的形式,参数可以带有默认值,定义的函数不会编译到css 中

1
2
3
4
5
6
7
8
9
10
11
.box (@color:#4d926f) {
color: @color
}

.header {
.box;
}

.footer {
.box(green);
}

编译后的css

1
2
3
4
5
6
7
.header {
color: #4d926f;
}

.footer {
color: #008000;
}

当定义的函数有多个参数时,调用时还有一种简便写法

1
2
3
4
5
6
7
.box (@width: 1px, @style: solid, @color: #4d926f) {
border: @arguments;
}

.header {
.box(2, dashed, #4d926f);
}

编译后的css

1
2
3
.header {
border: 2 dashed #4d926f;
}
  • 嵌套规则

Less 的嵌套和 Dom 结构基本一致,可以使代码更加清晰、简洁。

1
2
3
4
5
6
7
8
.wapper {
text-align: center;

a {
color: #4d926f;
text-decoration: none;
}
}

编译后的css

1
2
3
4
5
6
7
8
.wapper {
text-align: center;
}

.wapper a {
color: #4d926f;
text-decoration: none;
}

使用操作伪元素更加方便

1
2
3
4
5
6
7
8
a {
color: #4d926f;
text-decoration: none;

&:hover {
color: #438865
}
}

编译后的css

1
2
3
4
5
6
7
8
a {
color: #4d926f;
text-decoration: none;
}

a:hover {
color: #438865;
}

注:嵌套越多,匹配次数就越多,加载性能会越低,所以尽量少嵌套。

结语

我上面只提到了Less 常用的几个特性,它还有很多强大的功能,网上很多教程,我就不再具体说了。一方面是我自己也没有去深入的了解,因为实际的使用场景并不多,真正开发时我可能还是会敲css 代码。另一方面虽然有的功能的加入确实能提高css 的编写效率,它确实把css 复杂化了,失去了css 原有的东西。有人评论说Less 是为了功能而实现功能,到底该不该用争议也是很多。
本文参考CSS—LESS LESSCSS 中文网