less

less 是一门 CSS 预处理语言,它扩展了 CSS 语言,增加了变量、Mixin、函数等特性,使 CSS 更易维护和扩展。 less可以运行在 Node 或浏览器端。less (Leaner Style Sheets 的缩写) 是一门向后兼容的 CSS 扩展语言。
对我自己而言less已经用了很久,但是之前没有系统的去学习less,也没有仔细的看看文档,今天写这篇文章主要就是查漏补缺和复习知识点。

1. 相比css语法less的一些新的特性

a. 变量(Variables)
Less里面的变量都是以@作为变量的起始标识,变量名由字母、数字、_和-组成;
在一个文件里面定义的同名变量存在全局变量和局部变量的区别

1
2
3
4
5
6
7
8
9
10
11
12
@width: 10px;
@height: @width + 10px;

#div {
width: @width;
height: @height;
}
编译后为:
#div {
width: 10px;
height: 20px;
}

b. 混合(Mixins)
Mixins是一种将一组属性从一个规则集包含(“混入”)到另一个规则集的方法。
混合可以将一个定义好的class A轻松的引入到另一个class B中,从而简单实现class B继承class A中的所有属性。我们还可以带参数地调用,就像使用函数一样。

1
2
3
4
5
6
7
8
.bordered (@line: 1px){
border: @line solid red;
}

#div .title{
color: white;
.bordered(10px);
}

c. 嵌套(Nesting)
Less的这种写法好处是显而易见,标签层级结构清晰可见,并且能减少css代码量

1
2
3
4
5
6
7
8
9
10
11
12
13
#div {
width: 100px;
height: 100px;
.title{
color: red;
font-size: 26px;
}
&:after{
content: '';
display: inline-block;
font-size: 20px;
}
}

d. calc() 特例

1
2
@var: 50vh/2;
width: calc(50% + (@var - 20px));

e. 函数(Functions)

1
2
3
4
5
6
7
8
@base: #fff;
@width: 0.5;

.calss{
width: percentage(@width); // 50%
color: saturate(@base, 5%);
background-color: spin(lighten(@base, 25%), 8);
}

f. Maps

1
2
3
4
5
6
7
8
9
10
11
12
13
#color(){
primary: blue;
secondary: green;
}
.button {
color: #color[primary];
border: 1px solid #color[secondary];
}
//编译后
.button{
color: blue;
border: 1px solid green;
}

g. 作用域(scope)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@var: red;

#page {
@var: white;
#div {
color: @var; // white
}
}

------------------------------

@var1: red;

#page {
#div {
color: @var1; //white
}
@var1: white;
}
baishiwen wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!