文章目录
LESS 与 Sass 介绍与安装
LESS 基础语法
变量(Variables)
less代码:
@width: 10px;
@height: @width + 10px;
#header {
width: @width;
height: @height;
}
编译为:(css代码)
#header {
width: 10px;
height: 20px;
}
混合(Mixins)
混合(Mixin)是一种将一组属性从一个规则集包含(或混入)到另一个规则集的方法。假设我们定义了一个类(class)如下:
.bordered {
border-top: dotted 1px black;
border-bottom: solid 2px black;
}
在其它规则集中使用这些属性,只需像下面这样输入所需属性的类(class)名称即可,如下所示:
#menu a {
color: #111;
.bordered();
}
.post a {
color: red;
.bordered();
}
.bordered 类所包含的属性就将同时出现在 #menu a 和 .post a 中了。(注意,你也可以使用 #ids 作为 mixin 使用。)
嵌套(Nesting)
Less 提供了使用嵌套(nesting)代替层叠或与层叠结合使用的能力。假设我们有以下 CSS 代码:
#header {
color: black;
}
#header .navigation {
font-size: 12px;
}
#header .logo {
width: 300px;
}
用 Less 语言我们可以这样书写代码:
#header {
color: black;
.navigation {
font-size: 12px;
}
.logo {
width: 300px;
}
}
用 Less 书写的代码更加简洁,并且模仿了 HTML 的组织结构。
还可以使用此方法将伪选择器(pseudo-selectors)与混合(mixins)一同使用。下面是一个经典的 clearfix 技巧,重写为一个混合(mixin) (& 表示当前选择器的父级):