一、less介绍
Less(Leaner Style Sheets)是一种CSS预处理器,它在CSS的基础上增加了:
- 变量
- 混合(Mixins)
- 嵌套规则
- 运算
- 函数
- 导入等特性
二、less安装
1.node.js安装
2.浏览器环境使用
1 2
| <link rel="stylesheet/less" type="text/css" href="styles.less" /> <script src="https://cdn.jsdelivr.net/npm/less@4" ></script>
|
3. vscode使用安装插件即可

三、less变量
1 2
| 1.创建 .less后缀文件 2.会自动生成.css文件!!!
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| @colors: black; @backgroud-color: red; @width: 200px; @height: 200px; @border: 1px solid @color; @class: box2; @outline: outline; @primary: color; @color: red;
.@{class}{ color: @colors; background-color: @backgroud-color; width: @width; height: @height; border: @border; text-align: center; @{outline}: 1px solid @colors; }
#@{class}{ color: @colors; background-color: @backgroud-color; width: @width + 100; height: @height; border: @border; text-align: center; }
.box{ color: @colors; background-color: @backgroud-color; width: @width; height: @height; border: @border; text-align: center; }
.box3{ @{primary}: @@primary; }
|
四、less函数
1 2 3 4 5
| @backgroud-color: {background-color: red; width: 200px; height: 200px;};
.box{ @backgroud-color(); }
|
五、less嵌套
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| .center{ width: 200px; height: 200px; background-color: green;
.box{ width: 100px; height: 100px; background-color: blue;
#item{ width: 50px; height: 50px; background-color: red; } } }
<div class="center"> 我是爷爷 <div class="box"> 我是爸爸 <div id="item"> 我是儿子 </div> </div> </div> </div>
|
&连接符 (&表示上一级)
| 用法 |
语法示例 |
编译结果 |
说明 |
| 伪类 |
.btn { &:hover { } } |
.btn:hover {} |
生成伪类选择器 |
| 伪元素 |
.clearfix { &::after { } } |
.clearfix::after {} |
生成伪元素 |
| 类修饰 |
.btn { &.active { } } |
.btn.active {} |
并列类选择器 |
六、less混合方法
| 特性 |
语法 |
用途 |
| 带参数混合 |
.mixin(@param) { } |
可配置的样式 |
| 默认参数 |
.mixin(@param: value) { } |
提供默认值 |
| 命名参数 |
.mixin(@name: value) |
按名称传参 |
| 条件守卫 |
.mixin() when (条件) { } |
条件应用样式 |
| 命名空间 |
#namespace { .mixin() { } } |
组织混合 |
| 返回值 |
.mixin() { @var: value; } |
返回计算值 |
| 递归混合 |
.mixin(@n) when (@n > 0) { } |
循环生成 |
七、less继承
语法: &.extend()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| .animation{ background: blue; border: 1px solid #991515; padding: 10px; }
.cat{ &:extend(.animation); color: green; }
.dog{ &:extend(.animation); color: red; }
|
八、导入
1.基本导入 @import
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| .box{ width: 200px; height: 200px; background-color: aqua; }
@import "main";
.box{ .box(); }
|