LESS是什么?
less是一门CSS预处理语言。由于CSS本身并不是程序式语言,不方便维护和扩展,没有变量、函数、作用域等概念。而LESS在CSS的基础语法之上,引入了变量、Mixin混入、运算以及函数等功能,大大简化了CSS的编写,降低了CSS的维护成本。
本质上,LESS包含一套自定义的语法及一个解析器,写好的LESS文件会通过解析器编译生成CSS文件。LESS并没有建材CSS原有的特性,更不是用来取代CSS的,而是在现有的语法基础上,为CSS加入程序式语言的功能特性。所以,标准的CSS文件直接改成.less格式,LESS编译器可以完全识别。
使用
1.标签引入。
link标签rel属性值一定要为stylesheet/less
<link rel="stylesheet/less" href="style.less">
<script src="less.min.js"></script>
2.命令行使用npm安装
npm install -g less
编译:
lessc style.less style.css
编译并压缩文件:
lessc --clean-css styles.less styles.min.css
3.前端服务热调试(webpack)
需要配置webpack,webpack会帮你编译less文件,可以在js中Import进.less文件,像使用css那样使用less.
4.在js中调用编译器调试
var less = require('less');
less.render('.myclass { width: (1 + 1) }', function (e, output) {
console.log(output.css); // 输出 .myclass {width:2}
});
语法规则
1.值变量
变量
这里的变量指的是常量,只能定义一次。以@开头定义,使用时也要键入@
@color: #5B83AD;
@bgColor: @color + #111;
@width: 300px;
#wrap {
color: @color;
width: @width-20;
height: @width-20*5;
margin: (@width-20)*5;
background: @bgColor;
}
生成后的CSS:
#wrap {
color: #999;
width: 50%;
background: #6c94be;
}
2.选择器变量
让选择器变成动态的变量,使用时必须将变量名用花括号括起来
@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;
}
3.属性变量
将某CSS属性名当做变量,与选择器变量一样,使用时需要{}
@borderStyle: border-style;
@Solid: solid;
#wrap{
@{borderStyle}: @Solid;//变量名 必须使用大括号包裹
}
编译后:
#wrap{
border-style:solid;
}
4.url变量
@images: "../img"; //需要加引号
body {
background: url("@{images}/dog.png"); //变量名 必须使用大括号包裹
}
编译后:
body {
background: url("../img/dog.png");
}
5.声明规则集(作用类似于混入)
声明:@name:{属性:值};
使用:@name();
@background: {background:red;};
#main{
@background();
}
@Rules:{
width: 200px;
height: 200px;
border: solid 1px red;
};
#con{
@Rules();
}
编译后:
#main{
background:red;
}
#con{
width: 200px;
height: 200px;
border: solid 1px red;
}
嵌套:
&符:代表父选择器的名字
.boring {
display: inline-block;
&::after{
content:"Hello Less";
}
.class {
width: 100%;
}
&>.text{
height: 10px;
}
}
编译后:
.boring{
display: inline-block;
}
.boring::after{
content: "Hello Less";
}
.boring .class{
width: 100%;
}
.boring>.text{
height: 10px;
}
函数
1.类型函数
- isnumber 判定是否是数字
- iscolor 判断值是否是颜色
- isurl 判断是否是url
2.颜色操作
- saturate 增加一定数值的颜色饱和度
- lighteen 增加一定数值的颜色亮度
- darken 降低颜色亮度
- fade 给颜色设置一定数值的透明度
3.数学函数
- ceil 向上取整
- floor 向下取整
- round 四舍五入
- percentage 将浮点数值转换为百分比字符串
- abs 计算数值的绝对值
- pow 计算一个数的乘方
更多函数参见官方文档:http://lesscss.cn/functions/