目录
一、简介
less是一种动态样式语言,属于css预处理器的范畴,它扩展了css语言,增加了变量、Mixin、函数等特性,使css更易于维护和扩展
less既可以在客户端上运行,也可以借助Node.js在服务端运行。
二、基础
(一)变量
less可以通过“@”定义变量:
@color:pink; // 属性值变量
@m:margin; // 属性名变量
@selector:#wrap; // 选择器变量
* {
@{m}: 0;
background-color: @color;
}
@{selector} {
width:10px;
height:10px;
}
注:less中的变量存在类似于js变量提升的性质
(二)嵌套规则
可以类似于html那样使用,即子元素属性的样式代码可写在父元素的大括号下
如果需要使用伪类选择器,则需要在其开头加上“&”符,因为less在编译时默认会在两属性的样式代码中加上空格,导致选择出错:
#wrap{
width: 300px;
height: 400px;
position: relative;
.inner {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
&:hover {
background: pink;
}
}
}
// 加上&:#wrap .inner:hover
// 不加&:#wrap .inner :hover 多一个空格,导致hover没有加在inner上
(三)混合(mixin)
less可以让样式在文件中以类似于函数的形式存在,这样就可以将多个样式共同的部分(例如居中)提取成函数,当需要这部分样式时调用即可。
.center {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
.main {
position: relative;
width: 300px;
height: 400px;
.box1 {
.center;
background: red;
}
.box2 {
.center;
background: blue;
}
}
1、普通混合
类似于上段代码,以“.center”定义的“函数”就是普通混合
2、不带输出的混合
“.center()”,加上()就可以去掉输出(只能在当前文件中使用,不能编译到原生css文件中)
3、带参数的混合
.center(@h, @w, @c):
.center(@h, @w, @c) {
height: @h;
width: @w;
background: @c;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
.main {
position: relative;
width: 300px;
height: 400px;
.box1 {
.center(100px, 100px, red);
}
.box2 {
.center(50px, 50px, blue);
}
}
4、带参数并且有默认值的混合
.center(@h:100px, @w:100px, @c:red)
5、命名参数
调用时: .center(@c:black); // 宽高使用默认值,将背景颜色设置为黑色
6、匹配模式
另一种形式的参数
// "@_"包含所有的匹配模式,及无论传来什么样的模式该样式都会被调用
.sjx(@_, @w, @c) {
width: 0;
height: 0;
}
// 根据传来的匹配模式来对应地调用样式
.sjx(L, @w, @c) {
border: @w solid transparent;
border-left-color: @c;
}
.sjx(R, @w, @c) {
border: @w solid transparent;
border-right-color: @c;
}
.sjx(T, @w, @c) {
border: @w solid transparent;
border-top-color: @c;
}
.sjx(B, @w, @c) {
border: @w solid transparent;
border-bottom-color: @c;
}
调用:
.sjx(T, 10px, blue)
四、计算
加减乘除直接用符号即可,两个变量只需一个带单位就行,eg:100+100px = 200px
五、继承
// 将其写成类,不能带参数
.sjx {
width: 0;
height: 0;
}
// 继承并增加一些属性(重写)
.inner:extend(.sjx) {
border: 10px solid transparent;
border-left-color: blue;
}
||
.inner {
& :extend(.sjx);
border: 10px solid transparent;
border-left-color: blue;
}