less变量的基本用法

less中变量的基本用法

定义

使用@符号来定义变量

less转换为css的在线工具:
https://www.matools.com/less

使用:

1. 样式属性值

可以直接通过@variable来使用定义好的变量(最基本的用法)

@width:100px;
@height:@width+50px;

#container{
    width:@width;
    height:@height;
}

编译为:

#container {
    
    
  width: 100px;
  height: 150px;
}

选择器名称、属性名称、url和@import使用变量时(常用),变量必须以插值(变量名加上大括号)的形式使用。

2. 选择器名称

@panel-prefix-cls: antui-panel;
@panel-header: header;

.@{panel-prefix-cls}{
    background-color:#ffffff
}
#@{panel-header} {
    border-radius:2px
}

编译为:

.antui-panel {
    
    
  background-color: #ffffff;
}
#header {
    
    
  border-radius: 2px;
}

2. 属性名称

@property: color;

#header {
  @{property}:#fff;
  background-@{property}: #efefef;
}

编译为:

#header {
    
    
  color: #fff;
  background-color: #efefef;
}

3. url

@images: "../img";
  
body{
  background: url("@{images}/bg.png");
}

编译为:

body {
    
    
  background: url("../img/bg.png");
}

4. import

@header: "../../src/page/";

@import "@{header}/header/style/index.less";

编译为:

@import "../../src/page//header/style/index.less";

更多的用法

可以参考官方文档:https://less.bootcss.com/features/#variables

5. 变量的变量

使用一个变量引用另一个变量

@primary: #fafafa;

#header {
  @color:primary;
	.title{
      color:@@color;
  }
}

//#container{
//	color: @color; //The variable "@color" was not declared.
//}

编译为:

#header .title {
    
    
  color: #fafafa;
}
注意定义的变量也是有作用域的,@color在#header中定义的,在#container中使用报错。

6.Lazy Evaluation

类似于var定义的变量存在声明提升,less中定义的变量也可以在使用之后声明。
.header{
	width:@width;
}
@width: 100px;

编译为:

.header {
    
    
  width: 100px;
}
less中定义的变量存在作用域,后面定义的变量会覆盖前面同名的变量,在引用变量时首先在当前作用域中查找,没有在向上一层作用域查找直至最外层作用域。
@var: 10px;

.box{
  @var: 20px;
  .header{
 	width:@var; 
  }
  .content{
    width:@var;
    @var:30px;
  }
	
}

编译为:

.box .header {
    
    
  width: 20px;
}
.box .content {
    
    
  width: 30px;
}

7.$prop引用属性名

通过$prop可以直接引用已经使用的属性名作为变量 3.0版本才支持可能在线的一些转换工具还不支持(当前时间:2021-06-05)
.title{
  color:#eaeaea;
  background-color: $color;
  font-size: 5px;
  width: $font-size*5;
}

编译为:

.title {
    
    
    color: #eaeaea;
    background-color: #eaeaea;
    font-size: 5px;
    width: 25px;
}

如果引用的属性有重复的,后面的属性会覆盖掉前面的

.title {
  color: red; 
  h1 {
    background-color: $color; 
  }
  color: blue;  
} 

编译为:

.title {
    
    
    color: red;
    color: blue;
}

.title h1 {
    
    
    background-color: blue;
}

8.默认变量

默认变量使得可以通过在后面放置定义来覆盖变量

// Default Variables
@base-color: green;
@dark-color: darken(@base-color, 20%);  //深绿色

.footer {
    @base-color: red;
    color: @dark-color;
}

编译为:

.footer {
    
    
  color: #990000;
}

おすすめ

転載: blog.csdn.net/weixin_43398820/article/details/117598016