很早之前就听说过less了,但是一直拖着没去学习。最近抽空看了less,其实语法很简单,看一遍基本就知道怎么用了。但是问题又来了,那我在什么时候用less呢。平时自己写页面用less的话,感觉是方便了些,但是难道好处就只是这样?
刚好最近也在学习bootstrap,发现其源文件就是用less写的,看了之后,我才深深体会的less的强大,对less也有了更深一层的理解。
1、Less是什么?
LESS CSS是一种动态样式语言,属于CSS预处理语言的一种,它使用类似CSS的语法,为CSS的赋予了动态语言的特性,如变量、继承、运算、函数等,更方便CSS的编写和维护。
有些人可能没有接触过less,那我们就先可以简单的看看less的一些特性。
2、语言特性快速预览:
变量:
变量允许我们单独定义一系列通用的样式,然后在需要的时候去调用。所以在做全局样式调整的时候我们可能只需要修改几行代码就可以了。
LESS源码:
@color: #4D926F;#header { color: @color;}h2 { color: @color;}
编译后的CSS:
#header { color: #4D926F;}h2 { color: #4D926F;}
混合(Mixins)
混合可以将一个定义好的class A轻松的引入到另一个class B中,从而简单实现class B继承class A中的所有属性。我们还可以带参数地调用,就像使用函数一样。
LESS源码:
.rounded-corners (@radius: 5px) { -webkit-border-radius: @radius; -moz-border-radius: @radius; -ms-border-radius: @radius; -o-border-radius: @radius; border-radius: @radius;}#header { .rounded-corners;}#footer { .rounded-corners(10px);}
编译后的CSS:
#header { -webkit-border-radius: 5px; -moz-border-radius: 5px; -ms-border-radius: 5px; -o-border-radius: 5px; border-radius: 5px;}#footer { -webkit-border-radius: 10px; -moz-border-radius: 10px; -ms-border-radius: 10px; -o-border-radius: 10px; border-radius: 10px;}
嵌套
我们可以在一个选择器中嵌套另一个选择器来实现继承,这样很大程度减少了代码量,并且代码看起来更加的清晰。
LESS源码:
#header { h1 { font-size: 26px; font-weight: bold; } p { font-size: 12px; a { text-decoration: none; &:hover { border-width: 1px } } }}
编译后的CSS:
#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;}
函数和运算
运算提供了加,减,乘,除操作;我们可以做属性值和颜色的运算,这样就可以实现属性值之间的复杂关系。LESS中的函数一一映射了JavaScript代码,如果你愿意的话可以操作属性值。
新闻热点
疑难解答
图片精选