Less的一些常见操作

1,564 阅读1分钟

变量

声明变量时变量名前要加@

@width: 10px;

.class-name {
  width: @width;
}

混合

将一组属性应用到其他class类中,写法跟一般class写法相同,调用时是.混合名()

.mixins-name {
  width: 200px;
  height: 200px;
}

.mixins-color(@value) {
  color: @value;
}

.class-name {
  .mixins-name();
  .mixins-color(red);
}

命名空间和访问符

出于组织架构或者封装的目的,对混合进行分组(#命名空间名称),以便后期重用或维护

@color: red;
#namespace() {
  .width {
    width: 200px;
  }
  .bg-color {
    background: @color;
  }
}
.class-name {
  // 两种写法
  #namespace.width();
  #namespace > .bg-color;
}

映射

写法与命名空间类似

#colors() {
  primary: blue;
  secondary: green;
}

.class-name {
  background: #colors[primary];
}

继承extend

<template>
  <div class="sub-one">
    subClassOne
    <div class="aaa">1111111111111</div>
  </div>
  <div class="sub-two">subClassTwo</div>
</template>

<style lang="less" scoped>
.parent-class {
  background: red;
  .aaa {
    background: blue;
  }
}

.sub-one {
  width: 200px;
  &:extend(.parent-class); // 写法1
  &:extend(.parent-class .aaa); // 继承嵌套的选择器
}

.sub-two:extend(.parent-class) { // 写法2,提示{}中不能为空,故设置了width
  width: 100px;
}
</style>

image.png

嵌套

嵌套最好不要超过3层,否则影响性能

转义

允许使用任意字符串作为属性或变量值。任何~“anything”形式的内容都按原样输出

函数(了解)

less内置函数:less.bootcss.com/functions/

作用域

定义的变量或混合,若在本地找不到,就从父级作用域继承

导入

@import "地址/文件名.less"

less的使用方法介绍:blog.csdn.net/lhjuejiang/…

练习:通过递归创建多个样式类,可用于生成padding、margin等常用尺寸样式

<template>
  <div class="pd-5">1111111111</div>
  <div class="pd-10">1111111111</div>
  <div class="pd-15">1111111111</div>
  <div class="pd-20">1111111111</div>
  <div class="pd-25">1111111111</div>
</template>

<style lang="less" scoped>
.other {
  background: salmon;
  margin: 10px 0;
}

.padding(@i) when(@i <= 30) {
  .pd-@{i} {
    padding: @i + 0px;
    .other(); // 为了更直观看到效果,特在此处加了混合样式
  }
  .padding((@i + 5));
}
.padding(5);

// 上述循环编译成CSS代码如下
.pd-5 {
  padding: 5px;
}
.pd-10 {
  padding: 5px;
}
.pd-15 {
  padding: 5px;
}
.pd-20 {
  padding: 5px;
}
.pd-25 {
  padding: 5px;
}
</style>

image.png

<style lang="less" scoped>
// 生成margin、padding一些常用的尺寸样式
.magin-padding(@i) when(@i<=30) {
  .mt-@{i} {
    margin-top: @i + 0px;
  }
  .mb-@{i} {
    margin-bottom: @i + 0px;
  }
  .ml-@{i} {
    margin-left: @i + 0px;
  }
  .mr-@{i} {
    margin-right: @i + 0px;
  }
  .pt-@{i} {
    padding-top: @i + 0px;
  }
  .pb-@{i} {
    padding-bottom: @i + 0px;
  }
  .pl-@{i} {
    padding-left: @i + 0px;
  }
  .pr-@{i} {
    padding-right: @i + 0px;
  }
  .magin-padding(@i +5);
}
.magin-padding(5);

</style>