- 值变量
/* Less */
@color: #999;
@bgColor: skyblue;//不要添加引号
@width: 50%;
#wrap {
color: @color;
background: @bgColor;
width: @width;
}
/* 生成后的 CSS */
#wrap {
color: #999;
background: skyblue;
width: 50%;
}
在平时工作中,我们就可以把 常用的变量 封装到一个文件中,这样利于代码组织维护。
- 选择器变量
让选择器变成动态
/* Less */
@mySelector: #wrap;
@Wrap: wrap;
@{mySelector}{ //变量名 必须使用大括号包裹
color: #999;
width: 50%;
}
.@{Wrap}{
color:#ccc;
}
#@{Wrap}{
color:#666;
}
/* 生成的 CSS */
#wrap{
color: #999;
width: 50%;
}
.wrap{
color:#ccc;
}
#wrap{
color:#666;
}
- 属性变量
/* Less */
@borderStyle: border-style;
@Soild:solid;
#wrap{
@{borderStyle}: @Soild;//变量名 必须使用大括号包裹
}
/* 生成的 CSS */
#wrap{
border-style:solid;
}
- url变量 项目结构改变时,修改其变量即可。
/* Less */
@images: "../img";//需要加引号
body {
background: url("@{images}/dog.png");//变量名 必须使用大括号包裹
}
/* 生成的 CSS */
body {
background: url("../img/dog.png");
}
- 声明变量 有点类似于 下面的 混合方法
- 结构: @name: { 属性: 值 ;};
- 使用:@name();
/* Less */
@background: {background:red;};
#main{
@background();
}
@Rules:{
width: 200px;
height: 200px;
border: solid 1px red;
};
#con{
@Rules();
}
/* 生成的 CSS */
#main{
background:red;
}
#con{
width: 200px;
height: 200px;
border: solid 1px red;
}
- 变量运算
不得不提的是,Less 的变量运算完全超出我的期望,十分强大。
- 加减法时 以第一个数据的单位为基准
- 乘除法时 注意单位一定要统一
/* Less */
@width:300px;
@color:#222;
#wrap{
width:@width-20;
height:@width-20*5;
margin:(@width-20)*5;
color:@color*2;
background-color:@color + #111;
}
/* 生成的 CSS */
#wrap{
width:280px;
height:200px;
margin:1400px;
color:#444;
background-color:#333;
}
- &的用法
&:代表是上一层选择器的名字
/* Less */
#header{
&:after{
content:"Less is more!";
}
.title{
font-weight:bold;
}
&_content{//理解方式:直接把 & 替换成 #header
margin:20px;
}
}
/* 生成的 CSS */
#header::after{
content:"Less is more!";
}
#header .title{ //嵌套了
font-weight:bold;
}
#header_content{//没有嵌套!
margin:20px;
}