Начинаем работатать
Обзор Less, как скачать и использовать, примеры и др.
Обзор Less, как скачать и использовать, примеры и др.
Less является препроцессором CSS. Он расширяет язык CSS, добавляя такие возможности, как переменные, миксины, функции и многие другие техники, которые сделают Ваш CSS более поддерживаемым, «темизируемым» (да-да, речь про поддержку стилистически единых тем оформления) и расширяемым.
Less можно запустить внутри Node, в браузере и в 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
Результат компиляции будет выведен stdout
. Чтобы сохранить результат CSS в файл, укажите имя этого файла:
$ lessc styles.less styles.css
Для вывода минифицированный CSS, можно использовать плагин clean-css
. Когда плагин установлен, минификация вывода CSS задается опцией --clean-css
:
$ lessc --clean-css styles.less styles.min.css
To see all the command line options run lessc
without parameters or see Usage.
You can invoke the compiler from node, as such:
var less = require('less');
less.render('.class { width: (1 + 1) }', function (e, output) {
console.log(output.css);
});
which will output
.class {
width: 2;
}
You may pass some options to the compiler:
var less = require('less');
less.render('.class { width: (1 + 1) }',
{
paths: ['.', './lib'], // Specify search paths for @import directives
filename: 'style.less', // Specify a filename, for better error messages
},
function (e, output) {
console.log(output.css);
});
See Usage for more information.
See the Usage section for details of other tools.
Using less.js in the browser is great for development, but it's not recommended for production
Client-side is the easiest way to get started and good for developing with Less, but in production, when performance and reliability is important, we recommend pre-compiling using node.js or one of the many third party tools available.
To start off, link your .less
stylesheets with the rel
attribute set to "stylesheet/less
":
<link rel="stylesheet/less" type="text/css" href="styles.less" />
Next, download less.js and include it in a <script></script>
tag in the <head>
element of your page:
<script src="less.js" type="text/javascript"></script>
.less
stylesheet each of them is compiled independently. So any variables, mixins or namespaces you define in a stylesheet are not accessible in any other.Options are defined by setting them on a global less
object before the <script src="less.js"></script>
:
<!-- 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>
Or for brevity they can be set as attributes on the script and link tags (requires JSON.parse browser support or 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">
Learn more about Browser Options
Less is released under the Apache 2 License (though there are plans to dual license it). Copyright 2009-2018, 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.