less

71 阅读2分钟

变量声明

使用@声明变量,声明的变量具有就近原则

@card: red;
@box: box;

@{box} {
  color: @card;
}

.box {
  color: @card;
}

嵌套

&代替上一层级的选择器

.box{
  color: red;
  & .item{
    display: flex;
  }
}

混合

无参数

.card(){
  color: red;
}
.box{
  .card();
}

有参数

可以设置默认数值

.card(@color){
  color: @color;
}
.box{
  .card(#fff);
}

// 设置默认数值
.card(@color:red){
  color: @color;
}
.box{
  .card();
}

方法的命名空间

如果要使用子方法需要要调用父级的方法

.card() {
  .a(@w: 500px) {
    width: @w;

    .b(@h: 200px) {
      height: @h;
    }
  }
}

.box {
  .card>.a>.b
}

输出结果

.box {
  height: 200px;
}

方法条件限制 (判断)

使用when关键字用来判断条件的成立

使用when not 表示取反,使用when and表示并且,使用when 逗号表示或者

.card(@w) when (@w = 20px) {
  width: 20px;
}

.box {
  .card(200px)
}

方法循环 (循环)

.card(@n, @i: 1) when (@i <=@n) {
  .item-@{i} {
    width: @i;
  }

  .card(@n, (@i+1))
}
.box{
  .card(4)
}

属性拼接

+转译成逗号,+_转译成空格

.margin() {
  margin+_: 1px;
}
.box{
  .margin();
  margin+_:2px;
}

编译结果

.box {
  margin: 1px 2px;
}

继承 extend

使用 extend 关键字,可以继承多个使用逗号分开

.card{
  display: flex;
  justify-content: center;
  align-items: center;
}

.item{
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: red;
}

.box2{
  &:extend(.card,.item);
  text-decoration: none;
}

all关键字

使用all关键字可以继承所有的样式,默认情况下继承只是最外层的父级样式

.card{
  display: flex;
  justify-content: center;
  align-items: center;
  a{
    text-align: center;
  }
}

.box2{
  &:extend(.item all);
  text-decoration: none;
}

导入

使用关键字import,可以省略扩展名

@import "nav";

reference

reference 不会在引入的文件中进行编译,但是可以使用引入的变量和样式

@import (reference) "nav";

once

这意味着该文件只导入一次

@import (once) "nav";

multiple

用于允许导入多个同名文件

@import (multiple) "foo";

条件表达式

比较运算符号>,<,>=,<=,=

颜色函数

lightness

在HSL色彩空间中提取颜色对象的亮度通道。

.color(@color) when (lightness(@color) >50%) {
  background-color: #fff;
}

.color(@color) when (lightness(@color) <=50%) {
  background-color: #000;
}

.box{
  .color(red);
}

输出结果

.box {
  background-color: #000;
}

类型检测函数

  • iscolor
  • isnumber
  • isstring
  • iskeyword
  • isurl

函数

less支持所有函数