一、普通的变量
1. 变量的定义方式:@
2. 示例:
- less 文件:
@blue:#5B83AD; #header{ color:@blue; }
- 编译后的 css 文件:
#header { color: #5b83ad; }
二、作为选择器和属性名
1. 使用的时候将变量以“@{变量名}”的方式使用
2. 示例:
- html 文件:
<div class="width"></div>
- less 文件:
@mySelector:width; .@{mySelector}{ @{mySelector}:960px; height:500px; }
- 编译后的 css 文件:
.width { width: 960px; height: 500px; }
注意:这里的选择器即是选择器也是属性名,譬如将 class、@mySelector:width;
换成 widths 就会报错,不识别,因为 css 里面没有 widths 这个属性。
三、作为 url
1. 使用时用""将变量的值括起来,同样将变量以@{变量名}的方式使用
2. 示例
- less 文件:
@myUrl:"http://class.imooc.com/static/module/index/img"; body{ background:#ccc url("@{myUrl}/nav.png") no-repeat; }
- 编译后的 css 文件:
body { background:#cccccc url("http://class.imooc.com/static/module/index/img/nav.png") no-repeat; }
四、延迟加载
1. 变量是延迟加载的,在使用前不一定要预先声明。
2. 示例
- less 文件
.box{ background:@green; width:500px; height:500px; } @green:#801f77;
- 编译后的 css 文件
.box { background: #801f77; width: 500px; height: 500px; }