LESS 原理,一款css的预处理程序Less的使用指南教程
安装与使用:
//客户端引用
<link rel="stylesheet/less" type="text/css" href="styles.less">
<script src="less.js" type="text/javascript"></script>
//node服务端使用
npm install less
var less = require('less');//或者import less from 'less'
less.render('.class { width: 1 + 1 }', function (e, css) {
console.log(css);
});
//输出
.class {
width: 2;
}
客户端不建议直接引用less.js,可通过编译为css引入,推荐编译工具koala。
变量
定义变量用@
//less
@ly_width:100px;
.box {
width:@ly_width;
}
/*编译css*/
.box {
width:100px;
}
混合
混合可以将一个定义好的class A轻松的引入到另一个class B中,从而简单实现class B继承class A中的所有属性。我们还可以带参数地调用,就像使用函数一样。
// LESS
.rounded-corners (@radius: 5px) {
border-radius: @radius;
-webkit-border-radius: @radius;
-moz-border-radius: @radius;
}
#header {
.rounded-corners;
}
#footer {
.rounded-corners(10px);
}
/*生成的 CSS */
#header {
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
}
#footer {
border-radius: 10px;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
}
嵌套规则
实现样式的继承关系,代码看起来层次分明,提高代码可维护性
// LESS
#header {
p { font-size: 12px;
a { text-decoration: none;
&:hover { border-width: 1px }
}
}
}
* 生成的 CSS */
#header p {
font-size: 12px;
}
#header p a {
text-decoration: none;
}
#header p a:hover {
border-width: 1px;
}
函数 & 运算
运算提供了加,减,乘,除操作,还可以做属性值和颜色的运算…
//less
@ly_width:100px;
.one {
width:@ly_widht + 100;
}
/*生成css*/
.one {
idth:200px;
}
match函数:
round(1.67); //returns `2`
eil(2.4); //returns `3`
floor(2.6); //returns `2`)
Color函数:
lighten(@color, 10%); // return a color which is 10% *lighter* than @color
darken(@color, 10%); // return a color which is 10% *darker* than @color
saturate(@color, 10%); // return a color 10% *more* saturated than @color
desaturate(@color, 10%); // return a color 10% *less* saturated than @color
fadein(@color, 10%); // return a color 10% *less* transparent than @color
fadeout(@color, 10%); // return a color 10% *more* transparent than @color
fade(@color, 50%); // return @color with 50% transparency
spin(@color, 10); // return a color with a 10 degree larger in hue than @color
spin(@color, -10); // return a color with a 10 degree smaller hue than @color
mix(@color1, @color2); // return a mix of @color1 and @color2
命名空间
有时候,你可能为了更好组织CSS或者单纯是为了更好的封装,将一些变量或者混合模块打包起来, 你可以像下面这样在#bundle
中定义一些属性集之后可以重复使用
#bundle {
.button () {
display: block;
border: 1px solid black;
background-color: grey;
&:hover { background-color: white }
}
.tab { ... }
.citation { ... }
}
//你只需要在 #header a中像这样引入 .button:
#header a {
color: orange;
#bundle > .button;
}
作用域
LESS 中的作用域跟其他编程语言非常类似,首先会从本地查找变量或者混合模块,如果没找到的话会去父级作用域中查找,直到找到为止.
文件引用
一个less文件头部引入另一个less文件
@import "lib.less";
@import "lib";
注释
两种注释方式:
//这是注释哦…
/*这是注释*/