css预处理Less

什么是Less?

Less其实就是css预处理器,简单的说,就是动态编写css。css

Less用法

首先以vue中开发为例,先安装less和less-loadervue

npm install less less-loader

1.变量

1.变量值定义

格式: @变量名npm

@width:100px;
  .hello{
    width: @width;
  }

最终输出:less

.hello{
    width:100px;
  }

2.属性变量定义

格式:@{变量名}函数

@color:color;
  .hello{
    @{color}:blue;
  }

最终输出:code

.hello{
    color:blue;
  }

3.属性部件变量定义

格式:@{变量名}开发

@color:color;
  .hello{
    background-@{color}: red;
  }

最终输出:字符串

.hello{
    background-color: red;
  }

4.选择器定义

格式:@{变量名}get

@dialog:.dialog;
  @{dialog}{
     width:80px;
     height:80px;
     background: green;
  }

最终输出:scss

.dialog{
    width: 80px;
    height: 80px;
    background: green;
}

5.选择器部件定义

格式:@{变量名}

@fix:fix;
  .d-@{fix}{
    color:gold;
  }

最终输出:

.d-fix{
    color: gold;
}

2.混合(Mixins)

less中容许将已有的class或者id运用在不一样的选择器上

1.不带参数

.border{
    border:2px solid blue;
  }
  .hello{
    .border;
  }

最终输出:

.hello{
    border: 2px solid blue;
}

2.可带参数

.border(@border-wdith){
    border:@border-wdith solid palegreen;
  }
  .hello{
    .border(20px);
  }

最终输出:

.hello{
    border: 20px solid palegreen;
}

3.默认带值

.border(@border-width:10px){
    border:@border-width solid blue;
  }
  .hello{
    .border();
  }

最终输出:

.hello{
    border: 10px solid blue;
}

若是不想要默认值,能够.border(参数值)

3.匹配模式

.pos(r){
    position: relative;
  }
  .pos(a){
    position: absolute;
  }
  .pos(f){
    position: fixed;
  }
  .hello{
    .pos(f);
  }

最终输出:

.hello{
    position: fixed;
}

若:

.pos(@_){
    width:100px;
}

最终输出:

.hello{
    width:100px;
    position: fixed;
}

@_表示全部的.pos都必须带上里面的属性

4.运算

@width:20px;
  .hello{
    width: @width*2+10;
  }

最终输出:

.hello{
    width: 50px;
}

5.嵌套

.list{
    li{
      width:100px;
    }
  }

最终输出:

.list li{
    width: 100px;
}

less中悬浮:

.list{
    &:hover{
      background: red;
    }
  }

最终输出:

.list:hover{
      background: red;
  }

注意:&在less中是表示上一层选择器的意思

6.argument变量

.border(@border-width:3px,@x:solid,@c:black){
     border:@arguments;
  }
  .box{
    .border();
  }

最终输出:

.box{
    border: 3px solid black;
}

@arguments就是表示()中全部参数值

7.转义

格式:~"" 或者 ~''

@min768: ~"(min-width: 768px)";
  .hello {
    @media @min768 {
      font-size: 20px;
    }
  }

最终输出:

@media (min-width: 768px){
    .hello{
    font-size: 20px;
}
}

当less没法识别某个字符串的时候,就得用转义,防止编译错误

8.函数

less内置了不少用于转换颜色、处理字符串等函数,具体见官网地址:http://lesscss.cn/functions/

9.when条件判断

.mixin (@flag) when (@flag){
    font-weight: bold;
  }
  .hello{
    .mixin(true);
  }

最终输出:

.hello{
     font-weight: bold;
  }

当@flag为真的时候,就调用

相关文章
相关标签/搜索