使用 Less

在 Node、浏览器和第三方环境中使用 Less。如果需要一个通用的安装指导和概况介绍,请参考首页的 使用 Less 一节。

Compile .less files to .css using the command line

Heads up! If the command line isn't your thing, learn more about GUIs for Less.

Installing lessc for use globally

Install with npm

npm install less -g

and then you will have the lessc command available globally. For a specific version (or tag) you can add @VERSION after our package name, e.g. npm install less@1.6.2 -g.

Installing for node development

Alternatively if you don't use the compiler globally, you may be after

npm i less --save-dev

This will install the latest official version of lessc in your project folder, also adding it to the devDependencies in your project's package.json.

Note that a tilde version range will be automatically specified in package.json. This is good, as new patch releases of the latest version will be installable by npm.

Beta releases of lessc

Periodically, as new functionality is being developed, lessc builds will be published to npm, tagged as. These builds will not be published as a @latest official release, and will typically have a build number or alpha/beta/release candidate designation.

Since patch releases are non-breaking we will publish patch releases immediately and alpha/beta/candidate versions will be published as minor or major version upgrades (we endevour since 1.4.0 to follow semantic versioning).

Installing an unpublished development version of lessc

If you want to install a bleeding-edge, unpublished version of lessc, follow the instructions for specifying a git URL as a dependency and be sure to specify an actual commit SHA (not a branch name) as the commit-ish. This will guarantee that your project always uses that exact version of lessc.

The specified git URL may be that of the official lessc repo or a fork.

Server-Side and Command Line Usage

The binary included in this repository, bin/lessc works with Node.js on *nix, OSX and Windows.

Usage: lessc [option option=parameter ...] <source> [destination]

Command line usage

lessc [option option=parameter ...] <source> [destination]

If source is set to `-' (dash or hyphen-minus), input is read from stdin.

Examples

# compile bootstrap.less to bootstrap.css
$ lessc bootstrap.less bootstrap.css

# compile bootstrap.less to bootstrap.css and minify (compress) the result
$ lessc -x bootstrap.less bootstrap.css

Help

lessc --help
lessc --h

Prints a help message with available options and exits.

Include paths

lessc --include-path=PATH1;PATH2

Sets available include paths. Separated by ':' or ';' on Windows.

Use this to configure a list of paths which less will use to find imports in. You might use this for instance to specify a path to a library which you want to be referenced simply and relatively in the less files.

In node, set a paths option

{ paths: ['PATH1', 'PATH2']  }

Makefile

lessc -M
lessc --depends

No Color

lessc --no-color

No IE Compatability

lessc --no-ie-compat

Currently only used for the data-uri function to ensure that images aren't created that are too large for the browser to handle.

Disable JavaScript

lessc --no-js

Lint

lessc --lint
lessc --l

Runs the less parser and just reports errors without any output.

Silent

lessc -s
lessc --silent

Strict Imports

lessc --strict-imports

Allow imports from insecure https hosts

lessc --insecure

Version

lessc -v
lessc --version

Compress

lessc -x
lessc --compress

Compress using less built-in compression. This does an okay job but does not utilise all the tricks of dedicated css compression. Please feel free to improve our compressed output with a pull request.

Clean CSS

lessc --clean-css

Clean CSS is our minifer of choice if you want to get the most minified you can. This option switches it on.

Note - it does not yet support sourcemaps, for that you can only use our own compression.

Clean CSS Options

lessc --clean-css --clean-option=--selectors-merge-mode:ie8 --clean-option=--advanced

Use this to pass options to clean css. The default options are the safest, so are IE8 compatible.

Source Map Output Filename

lessc --source-map
lessc --source-map=file.map

Tells less to generate a sourcemap. If you have the sourcemap option without a filename it will use the source less file name but with the extension map.

Source Map Rootpath

lessc --source-map-rootpath=dev-files/

Specifies a rootpath that should be prepended to each of the less file paths inside the sourcemap and also to the path to the map file specified in your output css.

Use this option if for instance you have a css file generated in the root on your web server but have your source less/css/map files in a different folder. So for the option above you might have

output.css
dev-files/output.map
dev-files/main.less

Source Map Basepath

lessc --source-map-basepath=less-files/

This is the opposite of the rootpath option, it specifies a path which should be removed from the output paths. For instance if you are compiling a file in the less-files directory but the source files will be available on your web server in the root or current directory, you can specify this to remove the additional less-files part of the path

Source Map Less Inline

lessc --source-map-less-inline

This option specifies that we should include all of the css files in to the sourcemap. This means that you only need your map file to get to your original source.

This can be used in conjunction with the map inline option so that you do not need to have any additional external files at all.

Source Map Map Inline

lessc --source-map-map-inline

This option specifies that the map file should be inline in the output CSS. This is not recommended for production, but for development it allows the compiler to produce a single output file which in browsers that support it, use the compiled css but show you the non-compiled less source.

Source Map URL

lessc --source-map-url=../my-map.json

Allows you to override the URL in the css that points at the map file. This is for cases when the rootpath and basepath options are not producing exactly what you need.

Rootpath

lessc -rp=resources/
lessc --rootpath=resources/

Allows you to add a path to every generated import and url in your css. This does not effect less import statements that are processed, just ones that are left in the output css.

For instance, if all the images the css use are in a folder called resources, you can use this option to add this on to the URL's and then have the name of that folder configurable.

Relative URLs

lessc -ru
lessc --relative-urls

By default URLs are kept as-is, so if you import a file in a sub-directory that references an image, exactly the same URL will be output in the css. This option allows you to re-write URL's in imported files so that the URL is always relative to the base imported file. E.g.

# main.less
@import "files/backgrounds.less";
# files/backgrounds.less
.icon-1 {
  background-image: url('images/lamp-post.png');
}

this will output the following normally

.icon-1 {
  background-image: url('images/lamp-post.png');
}

but with this option on it will instead output

.icon-1 {
  background-image: url('files/images/lamp-post.png');
}

You may also want to consider using the data-uri function instead of this option, which will embed images into the css.

Strict Math

lessc -sm=on
lessc --strict-math=on

Defaults to Off.

Without this option on Less will try and process all maths in your css e.g.

.class {
  height: calc(100% - 10px);
}

will be processed currently.

With strict math on, only maths that is inside un-necessary parenthesis will be processed. For instance.

.class {
  width: calc(100% - (10px  - 5px));
  height: (100px / 4px);
  font-size: 1 / 4;
}
.class {
  width: calc(100% - 5px);
  height: 25px;
  font-size: 1 / 4;
}

We originally planned to default this to true in the future, but it has been a contraversial option and we are considering whether we have solved the problem in the right way, or whether less should just have exceptions for instances where / is valid or calc is used.

Strict Units

lessc -su=on
lessc --strict-units=on

Defaults to off.

Without this option, less attempts to guess at the output unit when it does maths. For instance

.class {
  property: 1px * 2px;
}

In this case, things are clearly not right - a length multiplied by a length gives an area, but css does not support specifying areas. So we assume that the user meant for one of the values to be a value, not a unit of length and we output 2px.

With strict units on, we assume this is a bug in the calculation and throw an error.

Global Variable

lessc --global-var="my-background=red"

This option defines a variable that can be referenced by the file. Effectively the declaration is put at the top of your base Less file, meaning it can be used but it also can be overridden if this variable is defined in the file.

Modify Variable

lessc --modify-var="my-background=red"

As opposed to the global variable option, this puts the declaration at the end of your base file, meaning it will override anything defined in your Less file.

URL Arguments

lessc --url-args="cache726357"

This option allows you to specify a argument to go on to every URL. This may be used for cache-busting for instance.

Line Numbers

lessc --line-numbers=comments
lessc --line-numbers=mediaquery
lessc --line-numbers=all

Generates inline source-mapping. This was the only option before browsers started supporting sourcemaps. We are consider deprecating, so please get in touch if you want this option to stick around.

Watch mode

To enable Watch mode, option env must be set to development. Then AFTER the less.js file is included, call less.watch(), like this:

<script src="less.js"></script>
<script>less.watch();</script>

Alternatively you can temporary enable Watch mode by appending #!watch to the URL.

Modify variables

Enables run-time modification of Less variables. When called with new values, the Less file is recompiled without reloading. Simple basic usage:

less.modifyVars({
  '@buttonFace': '#5B83AD',
  '@buttonText': '#D9EEF2'
});

Debugging

It is possible to output rules in your CSS which allow tools to locate the source of the rule.

Either specify the option dumpLineNumbers as above or add !dumpLineNumbers:mediaQuery to the url.

You can use the "comments" option with FireLESS and the "mediaQuery" option with FireBug/Chrome dev tools (it is identical to the SCSS media query debugging format).

Client-side Usage

Set options in a global less object before loading the less.js script:

<!-- set options before less.js script -->
<script>
  less = {
    env: "development",
    logLevel: 2,
    async: false,
    fileAsync: false,
    poll: 1000,
    functions: {},
    dumpLineNumbers: "comments",
    relativeUrls: false,
    globalVars: {
      var1: '"string value"',
      var2: 'regular value'
    },
    rootpath: ":/a.com/"
  };
</script>
<script src="less.js"></script>

Client side options

async

Type: Boolean

Default: false

Whether to request the import files with the async option or not. See fileAsync.

dumpLineNumbers

Type: String Options: |`comments`|`mediaQuery`|`all` Default:

When set this outputs source line information directly into the output css file. This helps you debug where a particular rule came from.

The comments option is used for outputting user understandable content, whilst mediaQuery is for use with a firefox extension which parses the css and extracts out the information.

In the future we hope this option to be superseded by sourcemaps.

env

Type: String Default: depends on page URL

Environment to run may be either development or production.

In production, your css is cached in local storage and information messages are not output to the console.

If the document's URL starts with file:// or is on local machine or has a non standard port, it will automatically be set to development.

e.g.

less = { env: 'production' };

errorReporting

Type: String

Options: html|console|function

Default: html

Set the method of error reporting when compilation fails.

fileAsync

Type: Boolean

Default: false

Whether to request the import asyncronously when in a page under a file protocol.

functions

Type: object

User functions, keyed by name.

e.g.

less = { functions: { myfunc: function() { return 1; }} };

and it can be used like a native Less function e.g.

.my-class {
  border-width: unit(myfunc(), px);
}

logLevel

Type: Number

Default: 2

The amount of logging in the javascript console. Note: If you are in the environment 'production' you will get no logging.

2 - Information and errors
1 - Errors
0 - Nothing

poll

Type: Integer

Default: 1000

The amount of time (in milliseconds) between polls while in watch mode.

relativeUrls

Type: Boolean

Default: false

Optionally adjust URLs to be relative. When false, URLs are already relative to the entry less file.

globalVars

Type: Object

Default: undefined

List of global variables to be injected into the code. Keys of the object are variables names, values are variables values. Variables of "string" type must explicity include quites.

rootpath

Type: String

Default: false

A path to add on to the start of every URL resource.

Less 只能运行在较新的浏览器上(新版的 Chrome、Firefox、Safari 和 IE)。我们不鼓励在生产环境中将 Less 用在客户端 - 因为会带来性能损失,当 Less 编译为 CSS 时,用户会看到延时(即使小于 1 秒钟),并且可能会引发 Javascript 报错。

再生产环境中将 Less 用于客户端也是有需求的,比如你希望让用户调整一些变量,能实时改变页面主题 - 这种情况下,用户不会担心等待一会儿,直到看到样式改变。

如果你希望在陈旧的浏览器上使用 Less,请使用 es-5 shim ,这将为浏览器增加一些 Less 所需要的 javascript 特性。

less2css.org

Online Integrated Development Environment (IDE) that is hosted in a browser allowing users to edit and compile Less to CSS in real-time.

winless.org/online-less-compiler

This Online Less Compiler can help you to learn Less. You can go through the examples below or try your own Less code.

lesstester.com

Online compiler for Less CSS.

dopefly.com/less-converter

A simple Less CSS file converter using the Less JS project.

lessphp.gpeasy.com/demo

less.php live demo.

leafo.net/lessphp/editor

lessphp live demo.

Online Web IDEs/Playgrounds with Less support

CSSDeck Labs

CSSDeck Labs is a place where you can quickly create some experiments (or testcases) that involves HTML, CSS, JS code.

CodePen

CodePen is a playground for the front end side of the web.

Fiddle Salad

An online playground with an instantly ready coding environment.

JS Bin

JS Bin is a webapp specifically designed to help JavaScript and CSS folk test snippets of code.

jsFiddle

Online Web Editor

Tip: try out the different Less tools available for your platform to see which one meets your needs.

This page focuses on GUI compilers. For command line usage and tools see Command Line Usage.

跨平台的编译器

Crunch!

Crunch is not just a Less compiler, it is also a Less editor for Windows and Mac.

If you work a lot with Less files, you should definitely try it out. Crunch is built on the Adobe AIR platform. Get more info: http://crunchapp.net/.

Crunch screenshot

Mixture

A rapid prototyping and static site generation tool for designers and developers

Mixture brings together a collection of awesome tools and best practices. It's quick, no-fuss, super-powerful and works with your favourite editor.

Get more info: http://mixture.io/

mixture screenshot

SimpLESS

SimpLESS is a minimalistic Less compiler. Just drag, drop and compile.

One of the unique features of SimpLESS is that it supports 'prefixing' your CSS by using http://prefixr.com.. SimpLESS is built on the Titanium platform. Get more info: http://wearekiss.com/simpless

SimpLESS screenshot

Koala

Koala is a cross-platform GUI application for compiling less, sass and coffeescript.

Features: cross platform, compile error notification supports and compile options supports.

Get more info: http://koala-app.com/

koala screenshot

特定平台的编译器

Windows

Prepros App

Prepros is a free and open source app that can compile less, sass, stylus, jade, haml and much more with live browser refresh.

Get more info at http://alphapixels.com/prepros

Prepros screenshot

WinLess

WinLess started out as a clone of Less.app, it takes a more feature-complete approach and has several settings. It also supports starting with command line arguments.

Get more info: http://winless.org

WinLess screenshot

OSx

LESS.app

LESS.app was the first GUI compiler for Less. LESS.app has a 'Compiler' tab where you can see the compiler results.

Get more info: http://incident57.com/less

LESS.app screenshot

CodeKit

CodeKit is the successor to LESS.app, and supports Less among many other preprocessing languages, such as SASS, Jade, Markdown, and many more.

Get more info: http://incident57.com/codekit

CodeKit screenshot

LiveReload

CSS edits and image changes apply live. CoffeeScript, SASS, Less and others just work.

Get more info: http://livereload.com

LiveReload screenshot

Linux

Plessc

Plessc is a gui fronted made with PyQT.

Auto compile, log viewer, open the less file with the editor choosen, settings for compile the file. Get more info: https://github.com/Mte90/Plessc

Plessc screenshot

另见: GUIs for Less.js

编辑器和集成开发工具

Sublime Text 2 & 3

Eclipse

Visual Studio

Dreamweaver

Notepad++ 6.x

Node.js 系编译器

  • assemble-less: Full-featured Grunt.js plugin for compiling Less files to CSS, with additional options for maintaining libraries of Less components and themes. For advanced users, this plugin allows you to define and manage Less "packages" or "bundles" using JSON, Lo-dash(underscore) templates (e.g. <%= bootstrap.less %>), and node-glob / minimatch (e.g. '../src/**/*.less"). assemble-less also has a number of options including minifying CSS
  • RECESS: Twitter's code quality tool for CSS built on top of Less. RECESS has options for compiling Less to CSS, as well as linting, formatting and minifying CSS.
  • autoless: A Less files watcher, with dependency tracking (changes to imported files cause other files to be updated too) and growl notifications.
  • Connect Middleware for Less.js: Connect Middleware for Less.js compiling

其他技术

Wro4j Runner CLI Download the wro4j-runner.jar file and run the following command:

java -jar wro4j-runner-1.5.0-jar-with-dependencies.jar --preProcessors lessCss`

More details can be found here: Wro4j Runner CLI

CSS::LESSp

http://search.cpan.org/~drinchev/CSS-LESSp/

lessp.pl styles.less > styles.css

Windows Script Host

Note - the official Less node runs on windows, so we are not sure why you would use this.

Less.js for Windows with this usage:

cscript //nologo lessc.wsf input.less [output.css] [-compress]

or

lessc input.less [output.css] [-compress]

dotless

dotless for Windows can be run like this:

dotless.Compiler.exe [-switches] <inputfile> [outputfile]

另见:

UI/Theme Frameworks and Components

Bootflat Open source Flat UI KIT based on Bootstrap
Bootstrap Front-end framework for developing responsive, mobile first projects on the web
Bootswatch Collection of free themes for Bootstrap
Cardinal Small "mobile first" CSS framework for front-end developers who build responsive web applications
CSSHórus Library for development of responsive and mobile websites
Flat UI Free Theme and framework for Bootstrap
frontsize CSS front end framework
InContent Image content with description created with CSS
Ink set of tools for quick development of web interfaces
JBST Theme framework that can be used as a standalone website builder or to create WordPress themes
KNACSS Minimalist, responsive and extensible style sheet to kick-start your HTML / CSS projects
Kube Minimalistic CSS-framework for developers and designers
Metro UI CSS Set of styles to create a site with an interface similar to Windows 8
Pre CSS framework
Schema Light, responsive, and lean frontend UI framework
UIkit Lightweight and modular front-end framework for developing web interfaces

Grid Systems

Fluidable
Golden Grid System
Order.less
responsibly
Responsive Boilerplate
Semantic.gs

Mixin Libraries

3L Mixins library
animate Library of CSS3 keyframe animations
Clearless Collection of mixins
CssEffects Collection of CSS style effects
Cssowl Mixin library
cube.less Animated 3D cube using only CSS
Hexagon Generate CSS hexagons with custom size and color
LESS Elements Set of mixins
LESS Hat Mixins library
LESS-bidi Set of mixins for creating bi-directional styling
media-query-to-type Media Queries to Media Types with Less
More-Colors.less Variables for easier color manipulation while you design in the browser
More.less Mixins, animations, shapes and more
Oban Collection of mixins
Preboot Collection of variables and mixins. The precursor to Bootstrap
Shape.LESS Collection of mixins for various shapes
tRRtoolbelt.less Mixins and functions for common actions

Thanks for thinking about contributing. Please read the contributing instructions carefully to avoid wasted work.

Install these tools

make sure the paths are setup. If you start your favourite command line and type node -v you should see the node compiler. If you run phantomjs -v you should see the phantomjs version number.

  • clone your less.js repository locally
  • navigate to your local less.js repository and run npm install this installs less' npm dependencies.
  • If you haven't used grunt before, run npm install grunt-cli -g - this allows you to use the "grunt" command anywhere

Usage

If you go to the root of the less repository you should be able to do grunt test - this should run all the tests. For the browser specific only, run grunt browsertest If you want to try out the current version of less against a file, from here do node bin/lessc path/to/file.less

To debug the browser tests, run grunt browsertest-server then go to http://localhost:8088/tmp/browser/ to see the test runner pages.

Optional: To get the current version of the less compiler do npm -g install less - npm is the node package manager and "-g" installs it to be available globally.

You should now be able to do lessc file.less and if there is an appropriate file.less then it will be compiled and output to the stdout. You can then compare it to running localy (node bin/lessc file.less).

Other grunt commands

  • grunt benchmark - run our benchmark tests to get some numbers on performance
  • grunt stable to create a new release
  • grunt readme to generate a new readme.md in the root directory (after each release)

Guide

If you look at http://www.gliffy.com/go/publish/4784259, This is an overview diagram of how less works.