一.什么是less
**1.因为 Less 和 CSS 非常像,因此很容易学习。而且 Less 仅对 CSS 语言增加了少许方便的扩展,这就是 Less 如此易学的原因之一。
2.less是动态的样式表语言,通过简单,明了的语法定义,使编写css 的工作变得非常简单,在实际项目开发中,大大提高了前端工程师的工作效率
3.css需要书写大量看似没有逻辑的代码,不方便维护及扩展,不利于复用,造成这些困难的很大原因源于css是一门非程序性语言,没有变量,函数,scope等概念
4.less在css基础上引入了变量,混入,运算以及函数等功能,大大简化了css的编写,并且降低了css的维护成本,less可以让我们用更少的代码做更多的事。
less 官网 https://less.bootcss.com/
插件安装
在vscode中安装 easy less 插件
二.如何使用less
1.在vscode中创建一个.less的文件,在里面写css,保存后会将less中的内容自动解析为css样式,在将css样式引入html中
2.注释
在less中
//式的注释不会被编译到css中
/* */ 式的注释会被编译到css中
3.变量
可以将样式的值赋给一个变量,在样式中引入这个变量
将:
@width: 10px;
@height: @width + 10px;
#header {
width: @width;
height: @height;
}
编译为:
#header {
width: 10px;
height: 20px;
}
//定义变量;
@col : red;
@sty: dashed;
@width:300px;
@height:50px;
ul{
width: @width;
height: @height;
border: 1px @sty @col;
}
4.混合变量
混合(Mixin)是一种将一组属性从一个规则集包含(或混入)到另一个规则集的方法
当前div,li,和ul 都需要一个红色一像素的边框,传统的方式:
div{
width: @width;
height: @height;
border: 1px solid red;
}
li{
border: 1px solid red;
}
ul{
border: 1px solid red;
}
使用混合,我们可以把共同的样式抽取过来
.border{
border: 1px solid @col;
}
div{
width: @width;
height: @height;
.border;
}
li{
.border;
}
ul{
.border;
}
带参混合
比如刚才的例子,当前div,li,和ul 都需要一个一像素的实线边框,但是我们想让每个边框的颜色不同
此时可以把颜色作为一个参数传入
// 把color变量作为参数传入
.border(@color){
border: 1px solid @color;
}
div{
width: @width;
height: @height;
//传入参数
.border(red);
}
li{
.border(green);
}
ul{
.border(pink);
}
5.运算
// 运算
@test_width : 500px;
div{
width: (@test_width+200);
height: 300px;
background-color: rgb(155, 116, 116);
}
6.嵌套规则
ul{
li{
a{
color: green;
// &代表山级元素
//当前表示选中了a
&:hover{
color: yellow;
}
}
}
}
7.匹配模式
- 相当于js中的if,但又不完全是
- 满足条件后才能匹配
.f(r){
position: relative;
}
.f(a){
position: absolute;
}
.f(f){
position: fixed;
}
ul{
li{
a{
.f(a);
top: 100px;
left: 300px;
}
}
}