Nag Nag @%^#@#@$(*)!#@$

I'm Loading...

Aha!I'm PaoSuan,Please call me Mr.Pao.

Do more with {Less}

2012年02月5日

Less

什么是Less?

Less是一种动态样式语言。为什么称它是一种语言呢?因为它将 CSS 赋予了动态语言的特性,如变量,继承,运算,函数等。Less 既可以在客户端上运行(支持IE 6+, Webkit, Firefox),也可以借助 Node.js在服务端运行。

为什么要用Less?

  1. 为了写更少的代码
  2. 为了提高写代码的效率,减少重复劳动,解放生产力
  3. 为了更方便的维护我们写过的代码
  4. 为了让我们写的代码能够在一个或者多个项目中复用

总之,Less即将改变我们组织CSS代码的方式。相信我,如果你有CSS的知识基础,那么Less对你而言简直是小菜一碟,你学起来就会感到异常的容易。

Less都有哪些让人眼前一亮新特性?

  1. 变量(让人性奋)
  2. 混合(这玩意儿很有码感)
  3. 嵌套规则(让代码结构更美)
  4. 函数 & 运算(丫的更像编程了)

1、变量

利用变量,我们可以单独定义一系列通用的样式,在需要的时候去调用,这样的好处就是在通用属性需要修改的时候只需要改动我们定义的几行代码就行了,而不需要我们再去一行行的改动每一处有引用的地方。

1
2
3
4
5
6
7
8
9
10
//LESS
@color: #4D926F;
 
#header {
	color: @color;
}
 
h2 {
	color: @color;
}

经过Less编译后的代码如下:

1
2
3
4
5
6
7
#header {
	color: #4D926F;
}
 
h2 {
	color: #4D926F;
}

2、混合

混合可以让我们方便的把某一个定义过的Class A引用到另一个Class B中,从而可以实现方便的样式继承,除此之外,我们还可以实现带参数的调用,就好比调用函数一样简单。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//LESS
 
.radius (@radius: 5px) {
	border-radius: @radius;
	-webkit-border-radius: @radius;
	-moz-border-radius: @radius;
}
 
#header {
	.rounded-corners;
}
 
#footer {
	.rounded-corners(10px);
}

编译后的CSS代码如下:

1
2
3
4
5
6
7
8
9
10
11
#header {
	border-radius: 5px;
	-webkit-border-radius: 5px;
	-moz-border-radius: 5px;
}
 
#footer {
	border-radius: 10px;
	-webkit-border-radius: 10px;
	-moz-border-radius: 10px;
}

3、嵌套规则

有了嵌套规则,我们可以在一个选择器中嵌套另一个选择器来实现继承,从而大大减少了我们的代码量,并且让我们的代码结构更加的清晰易懂。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//LESS
 
#header {
	h1 {
		font-size: 26px;
		font-weight: bold;
	}
 
	p { font-size: 12px;
		a {
			text-decoration: none;
			&:hover { border-width: 1px }
		}
	}
}

编译后的CSS代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#header h1 {
	font-size: 26px;
	font-weight: bold;
}
 
#header p {
	font-size: 12px;
}
 
#header p a {
	text-decoration: none;
}
 
#header p a:hover {
	border-width: 1px;
}

4、函数 & 运算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//LESS
 
@the-border: 1px;
@base-color: #111;
@red: #842210;
 
#header {
	color: @base-color * 3;
	border-left: @the-border;
	border-right: @the-border * 2;
}
 
#footer { 
	color: @base-color+#003300;
	border-color: desaturate(@red,10%);
}

编译后的CSS代码如下:

1
2
3
4
5
6
7
8
9
10
#header {
	color: #333;
	border-left: 1px;
	border-right: 2px;
}
 
#footer { 
	color: #114411;
	border-color: #7d2717;
}