Less-变量

变量

基本使用

index.html

<div id="box"></div>

index.less

@width:100px;
@height: @width+10px;
.box{
  width: @width;
  height: @height;
  background-color: orange;
}

编译后的代码index.css

 

less使用@当做关键字来定义一个变量,这个变量就可以在css的属性中使用

注意,设置变量后面一定要加分号结尾,否则会报错;

变量也有自己的作用域

@width:100px;
@height: @width+10px;
.box{
  @width: 200px;
  width: @width;
  height: @height;
  background-color: orange;
}

上面代码中在全局的位置定义了@width为100px,然后在.box中再次定义了@width:200px;

.box内部的@height是210px,而不是全局@height的110px

我们看一下编译后的结果

 

 

 变量除了可以设置属性之外,还可以设置选择器

@selector: .box;

@{selector} {
  width: 200px;
  height: 200px;
  background: blue;
}

@**设置的变量可以使用 @{**}来获取

 

 

可以设置到css属性中

@colors: 123;
.box{
  width: 200px;
  height: 200px;
  background: rgb(100,200,@colors)
}

 

 

 还可以加到import导入的样式中,新建一个index.less文件

body{
  background: skyblue;
}

index.less

@import "./index2.less";
.box{
  width: 200px;
  height: 200px;
  background: rgb(100,150,220)
}

posted @ 2021-10-30 22:23  keyeking  阅读(160)  评论(0编辑  收藏  举报