Less 基本用法

环境检测


image.png

检测node.js, node -v
检测 npm(node package manager) , npm -v

image.png

检测 Less, lessc -v

注释

/注释/ 在Less中,这种格式的注释能被编译, // 这种不能;

/*注释*/

编译结果:也是 /注释/
截图对比:左边是less环境,右边是编译后的css

image.png

变量

@变量名:值;

@baseColor:#e92322;
a{
    color:@baseColor;
}

定义一个基本颜色变量,在 a 标签中引入;
看编译结果:

a {
  color: #e92322;
}

截图对比:左边是less环境,右边是编译后的css


image.png

混入

可以将一个定好的样式,引入到另一个样式中,类似于函数的调用;
先定义一个基本样式,设置样式参数,并设置默认值

/* 定义一个类似函数的样式,@r 是圆角变量,:10px 是默认值*/
.addRadius(@r:10px){
    border-radius:@r;
    -webkit-border-radius:@r;
    -moz-border-radius:@r;
}
.mydiv{
    width: 100px;
    height: 100px;
    /*引入写好的样式,并传入参数*/
    .addRadius(); 
}

编译结果:

.mydiv {
  width: 100px;
  height: 100px;
  /*引入写好的样式,并传入参数,不使用参数的话,使用默认值 10px*/
  border-radius: 10px;
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
}

截图对比:


image.png

嵌套

实现选择器继承,可以减少代码量,同时使用代码结构更清晰

传统写法:

.my-header{}
.my-header > div{}
.my-header > div > h3{}
.my-header > div > h3::before{}
.my-header > div > h3 > a{}
.my-header > div > h3 > a:hover{}

Less 嵌套写法:

.my-header{
    width: 200px;
    height: 36px;
    .addRadius();
    > div{
        width: 100%;
        > h3 {
            height: 20px;
            &::before{
                content: "";
                display: table;
            }
            > a{
                text-decoration: none;
                &:hover{
                    text-decoration: underline;
                }
            }
            
        }
        
    }
}

编译结果:

.my-header {
  width: 200px;
  height: 36px;
  border-radius: 10px;
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
}
.my-header > div {
  width: 100%;
}
.my-header > div > h3 {
  height: 20px;
}
.my-header > div > h3::before {
  content: "";
  display: table;
}
.my-header > div > h3 > a {
  text-decoration: none;
}
.my-header > div > h3 > a:hover {
  text-decoration: underline;
}

截图对比:


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容