Less 中文
Less概述,包括如何下载,使用,示例以及更多。
Less概述,包括如何下载,使用,示例以及更多。
Less 是一门 CSS 预处理语言,它扩展了 CSS 语言,增加了变量、Mixin、函数等许多特性,使 CSS 更易维护和扩展。
Less可以在node,browser和Rhino环境中运行 。同时,Less允许使用很多第三方工具编译和监听文件。测试Less最便捷的方式可以通过使用 Less在线编辑器。
例子:
@base: #f938ab;
.box-shadow(@style, @c) when (iscolor(@c)) {
-webkit-box-shadow: @style @c;
box-shadow: @style @c;
}
.box-shadow(@style, @alpha: 50%) when (isnumber(@alpha)) {
.box-shadow(@style, rgba(0, 0, 0, @alpha));
}
.box {
color: saturate(@base, 5%);
border-color: lighten(@base, 30%);
div { .box-shadow(0 0 5px, 30%) }
}
编译为
.box {
color: #fe33ac;
border-color: #fdcdea;
}
.box div {
-webkit-box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}
Less 可以通过npm在命令行中使用, 以及作为浏览器的脚本文件下载,或在各种各样的第三方工具中使用。 查看使用 章节获取更多具体信息。
在服务器上安装Less的最简单的方法是通过npm,node.js软件包管理器,如下所示:
$ npm install -g less
安装完成后,可以从命令行调用编译器,如下所示:
$ lessc styles.less
这将输出编译的CSS文件到stdout
。 要将CSS结果保存到你选择的文件,请使用:
$ lessc styles.less styles.css
如果要输出压缩的CSS文件,你可以使用clean-css
插件。 安装插件后,用--clean-css
选项指定输出压缩的CSS文件:
$ lessc --clean-css styles.less styles.min.css
要查看所有命令行选项,请不带参数运行lessc
,或者参阅使用方法。
你可以从node中调用Less编译器,如下所示:
var less = require('less');
less.render('.class { width: (1 + 1) }', function (e, output) {
console.log(output.css);
});
输出如下:
.class {
width: 2;
}
你可以将一些配置选项传递给编译器:
var less = require('less');
less.render('.class { width: (1 + 1) }',
{
paths: ['.', './lib'], // 指定@import指令的搜索路径
filename: 'style.less', // 指定一个文件名称, 以更好的输出错误信息
},
function (e, output) {
console.log(output.css);
});
更多相关信息,请参阅使用方法。
其他工具的详细信息,请参见使用方法章节。
在浏览器中使用less.js对开发很有帮助, 但不推荐用于生产环境
客户端安装是Less最简单的安装方式,不过这种方式只适用于开发环境,因为在生产环境中,系统的性能和可靠性尤为重要, 所以我们建议使用node.js或其他第三方工具来预编译。
首先,通过将rel
属性设置为"stylesheet/less
"来连接你的 .less
样式表:
<link rel="stylesheet/less" type="text/css" href="styles.less" />
然后, 下载 less.js并将其包含在页面的<head>
元素的<script></script>
标签中:
<script src="less.js" type="text/javascript"></script>
.less
样式表时,每个样式表都是独立编译的。因此,在样式表中定义的任何变量,mixins或名称空间都不能被其他任何样式表访问。选项通过在<script src="less.js"></script>
之前 之前将其设置在全局less
对象上来定义的:
<!-- set options before less.js script -->
<script>
less = {
env: "development",
async: false,
fileAsync: false,
poll: 1000,
functions: {},
dumpLineNumbers: "comments",
relativeUrls: false,
rootpath: ":/a.com/"
};
</script>
<script src="less.js"></script>
或者为了简洁起见,可以将它们设置为脚本和链接标记的属性(需要JSON.parse浏览器支持或polyfill)。
<script src="less.js" data-poll="1000" data-relative-urls="false"></script>
<link data-dump-line-numbers="all" data-global-vars='{ myvar: "#ddffee", mystr: "\"quoted\"" }' rel="stylesheet/less" type="text/css" href="less/styles.less">
详细了解浏览器选项
Less is released under the Apache 2 License (though there are plans to dual license it). Copyright 2009-2017, Alexis Sellier and the Less Core Team (see about). Boiled down to smaller chunks, it can be described with the following conditions.
The full Less license is located in the project repository for more information.