Make the LESS

A dynamic style language.

LESS gives CSS dynamic language features such as variables, inheritance, operations, and functions. LESS can be run on either a client (IE 6+, Webkit, Firefox) or a server with Node.js or Rhino. Version 1.3.1 LESS can be written as CSS: @base:#f938ab;.box-shadow(@style, @c) when (iscolor(@c)) { box-shadow: @style @c; -webkit-box-shadow: @style @c; -moz-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%)}} Import your style file before importing less: <link rel="stylesheet/less" type="text/css" href="styles.less">
<script src="less.js" type="text/javascript"></script>
Copy the code

variable

Variables allow us to define a single set of common styles that can then be called when needed. So we may only need to change a few lines of code to make a global style change. // LESS @color:#4D926F;

#header {color: @color; } h2 { color: @color; } /* Generated CSS */#header {
  color: #4D926F;
}
h2 {
  color: #4D926F;
}
Copy the code

hybrid

Mixing can easily introduce A defined class A into another class B, making it easy for class B to inherit all attributes from class A. We can also call them with arguments, just like we would with a function. // LESS .rounded-corners (@radius: 5px) { border-radius: @radius; -webkit-border-radius: @radius; -moz-border-radius: @radius; }#header {
  .rounded-corners;
}
#footer {.rounded-corners(10px); } /* Generated 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;
}
Copy the code

Nested rules

We can implement inheritance by nesting a selector within another selector, which greatly reduces the amount of code and makes the code look cleaner. // LESS#header {h1 { font-size: 26px; font-weight: bold; } p { font-size: 12px; a { text-decoration: none; &:hover {border-width: 1px}}}} /*#header h1 {
  font-size: 26px;
  font-weight: bold;
}
#header p {
  font-size: 12px;
}
#header p a {
  text-decoration: none;
}
#header p a:hover {
  border-width: 1px;
}
Copy the code

Function & operation

Operations provide addition, subtraction, multiplication, and division operations; We can do property values and colors, so that we can achieve complex relationship between property values. The functions in LESS map JavaScript code one by one, allowing you to manipulate property values if you wish. // LESS @the-border: 1px; @base-color:# 111;
@red:        # 842210;

#header {
  color: @base-color * 3;
  border-left: @the-border;
  border-right: @the-border * 2;
}
#footer { 
  color: @base-color + # 003300;border-color: desaturate(@red, 10%); } /* Generated CSS */#header {
  color: # 333;
  border-left: 1px;
  border-right: 2px;
}
#footer { 
  color: # 114411;
  border-color: #7d2717;
}
Copy the code

Used on the client

When importing your.less style file, set the rel attribute to "stylesheet/less" : <link rel="stylesheet/less" type="text/css" href="styles.less"> Then click the Download button at the top of the page to download less.js and import: <script SRC = in <head>"less.js" type="text/javascript"< span style = "box-sizing: border-box; color: RGB (50, 50, 50); line-height: 22px; font-size: 14px! Important; word-break: inherit! Important;" Note: Please use in server environment! Open the local directly may report an error!Copy the code

Monitoring mode

Monitor mode is a client feature that allows the client to automatically refresh when you change the style. To use it, just add it after the URL'#! watch'", and then refresh the page. Alternatively, you can start monitoring mode by running less. Watch () on the terminal. The easiest way to install LESS on the server is via NPM (node's package manager), like this: $ npm install less@latestCopy the code

use

Once LESS is installed, you can call the compiler in Node like this: var LESS = require('less');

less.render('.class { width: 1 + 1 }'.function(e, css) { console.log(css); }); Class {width: 2; } You can also call the parser and compiler manually: var parser = new(less.parser); parser.parse('.class { width: 1 + 1 }'.function (err, tree) {
    if (err) { return console.error(err) }
    console.log(tree.toCSS());
});
Copy the code

configuration

Var parser = new(less.parser)({paths: [paths:]'. '.'./lib'], // Specify search paths for @import directives
    filename: 'style.less' // Specify a filename, for better error messages
});

parser.parse('.class { width: 1 + 1 }'.function (e, tree) {
    tree.toCSS({ compress: true }); // Minify CSS output
});
Copy the code

On the command line

You can call the LESS parser at the terminal: $lessc styles. LESS the command above will pass the compiled CSS to stdout, which you can save in a file: $lessc styles.less > styles.css If you want to compress the compiled CSS, add -x.Copy the code

LESS grammar

LESS as a form of CSS extension, it does not castrate the functions of CSS, but in the existing CSS syntax, adding a lot of additional functions, so learning LESS is an easy thing, be sure to learn it!Copy the code

variable

It's easy to understand: @nice-blue:#5B83AD;
@light-blue: @nice-blue + # 111;

#header { color: @light-blue; }Output:#header { color: #6c94be; }You can even define a variable by its name: @fnord:"I am fnord.";
@var: 'fnord'; content: @@var; Content:"I am fnord."; Note that the variables in LESS are completely 'constant', so you can only define them once.Copy the code

hybrid

In LESS we can define a common set of attributes as a class and then call those attributes in another class. Class:.bordered {border-top: curtained 1px black; border-bottom: solid 2px black; } So if we now need to introduce those generic attribute sets in other classes, we can just call them in any class like this:#menu a {
  color: # 111;.bordered; } .post a { color: red; .bordered; }.bordered class properties will be styled#menu a and.post a

#menu a {
  color: # 111;border-top: dotted 1px black; border-bottom: solid 2px black; } .post a { color: red; border-top: dotted 1px black; border-bottom: solid 2px black; } Any CSS class, ID, or set of element attributes can be imported in the same way.Copy the code

Mixing with parameters

In LESS, you can also define a set of attributes with parameters as a function:.border-radius (@radius) {border-radius: @radius; -moz-border-radius: @radius; -webkit-border-radius: @radius; } then call it from another class like this:#header {.border-radius(4px); } .button { .border-radius(6px); Border-radius (@radius: 5px) {border-radius: @radius; -moz-border-radius: @radius; -webkit-border-radius: @radius; } So now if we call it like this:#header {.border-radius; } radius will have a value of 5px. You can also define a property set with no parameters. If you want to hide the property set from the CSS, but you want to refer to it in other property sets, you will find this method very useful:wrap () {
  text-wrap: wrap;
  white-space: pre-wrap;
  white-space: -moz-pre-wrap;
  word-wrap: break-word; } pre {.wrap} Output: pre {text-wrap: wrap; white-space: pre-wrap; white-space: -moz-pre-wrap; word-wrap:break-word;
}
Copy the code

@ the arguments variable

@arguments包含了所有传递进来的参数. 如果你不想单独处理每一个参数的话就可以像这样写:

.box-shadow (@x: 0, @y: 0, @blur: 1px, @color: # 000) {box-shadow: @arguments; -moz-box-shadow: @arguments; -webkit-box-shadow: @arguments; } .box-shadow(2px, 5px); It will print: box-shadow: 2px 5px 1px# 000;
  -moz-box-shadow: 2px 5px 1px # 000;
  -webkit-box-shadow: 2px 5px 1px # 000;
Copy the code

Pattern matching and guiding expressions

In some cases, we want to change the default rendering of the mix based on the parameters passed in, such as the following example:.mixin (@s, @color) {... } .class { .mixin(@switch,# 888);{color: darken(@color, 10%); } .mixin (light, @color) { color: lighten(@color, 10%); } .mixin (@_, @color) { display: block; } Now, if run: @switch: light; .class { .mixin(@switch,# 888);}} will get the following CSS:.class {color:#a2a2a2;display: block; } As above,.mixin will get the light color of the incoming color. If @switch is dark, it's going to be dark. The implementation is as follows: The first mixed definition is not matched because it only accepts dark as the first argument. The second mixed definition is successfully matched because it only accepts light. The third mixed definition is successfully matched because it accepts any value. A variable can match any incoming value, while a fixed value other than a variable matches only the incoming value that is equal to it. We can also match multiple parameters:.mixin (@a) {color: @a; } .mixin (@a, @b) { color: fade(@a, @b); } Nowif we call .mixin with a single argument, we will get the output of the first definition, but if we call it with two arguments, we will get the second definition, namely @a faded to @b.
Copy the code

guide

Guidance is useful when we want to match against expressions rather than values and parameters. If you're familiar with functional programming, you've probably already used homing. To preserve CSS declarability as much as possible, LESS guides blending instead ofif/elseStatement, as the former is defined in the @Media Query feature. .mixin (@a) when (lightness(@a) >= 50%) {background-color: black; } .mixin (@a) when (lightness(@a) < 50%) { background-color: white; } .mixin (@a) { color: @a; } the when keyword is used to define a homing sequence (in this case there is only one homing). Class1 {.mixin(.mixin);#ddd) }
.class2 { .mixin(#555) }Class1 {background-color: black; color:#ddd;
}
.class2 {
  background-color: white;
  color: # 555;} All comparisons available in guidance are: > >= = =< <. Also, keywordstrue.truth (@a) when (@a) {... } .truth (@a) when (@a =true) {... } Remove keywordstrueAll other values are treated as Boolean false:.class {.truth(40); // Will not match any of the above definitions.} The guiding sequence uses comma, ', '-- split, and is considered a match if and only if all conditions are met. .mixin (@a) when (@a > 10), (@a < -10) { ... } guide can have no parameters, can also compare parameters: @media: mobile; .mixin (@a) when (@media = mobile) { ... } .mixin (@a) when (@media = desktop) { ... } .max (@a, @b) when (@a > @b) { width: @a } .max (@a, @b) when (@a < @b) { width: Finally, if we want to match based on the type of value, we can use the is* function:.mixin (@a, @b: 0) when (isnumber(@b)) {... } .mixin (@a, @b: black) when (iscolor(@b)) { ... } Iscolor isnumber isString iskeyword isURL If you want to determine whether a value is a pure number or a unit, use the following function: .mixin (@a) when (isnumber(@a)) and (@a > 0) {... Mixin (@b) when not (@b > 0) {... }Copy the code

Nested rules

LESS allows us to write cascading styles in a nested manner. Let's look at the following CSS first:#header { color: black; }
#header .navigation {
  font-size: 12px;
}
#header .logo { 
  width: 300px; 
}
#header .logo:hover {text-decoration: none; } in LESS, we can write:#header {color: black; .navigation { font-size: 12px; } .logo { width: 300px; &:hover {text-decoration: none}}}#header { color: black;.navigation { font-size: 12px } .logo { width: 300px; &:hover {text-decoration: none}} / hover {text-decoration: none}} Note the use of the ampersand symbol - if you want to write concatenated selectors instead of descendant selectors, you can use ampersand. This is especially useful for dummy classes such as :hover and :focus. For example:.bordered {&.float {float: left; } .top { margin: 5px; }} output.bordered.float {float: left;  
}
.bordered .top {
  margin: 5px;
}
Copy the code

operation

Any number, color, or variable can be used. Let's take a look at some examples: @base: 5%; @filler: @base * 2; @other: @base + @filler; color:# 888/4;
background-color: @base-color + # 111;height: 100% / 2 + @filler; LESS has gone beyond our expectations and can distinguish between colors and units. @var: 1px + 5; LESS will print 6px. Parentheses are also allowed: width: (@var + 5) * 2; Border: (@width * 2) solid black;Copy the code

The Color function

LESS provides a series of color operations. The color is first converted to HSL color space and then manipulated at the channel level: 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);    // returnA mix of @color1 and @color2#f04615;.class { color: saturate(@base, 5%); background-color: lighten(spin(@base, 8), 25%); } You can also extract the color information: hue(@color); // returns the `hue` channel of @color saturation(@color); // returns the `saturation` channel of @color lightness(@color); // returns the'lightness'These functions are useful if you want to create a different color on the same color channel. For example: @new: HSL (Hue (@old), 45%, 90%); @New will maintain @old's hue, but with a different saturation and brightness.Copy the code

Math

LESS provides a handy set of mathematical functions that you can use to handle numeric types of values: round(1.67); / / returns ` 2 ` ceil (2.4); / / returns ` 3 ` floor (2.6); Returns' 2 'If you want to convert a value to a percentage, you can use the percentage function: percentage(0.5); // returns `50%`Copy the code

The namespace

Sometimes, you may want to pack variables or mixed modules together for better organization of CSS or simply for better encapsulation. You can do this in the followingYou can reuse a set of properties once you define them in the bundle:

#bundle {
  .button() { display: block; border: 1px solid black; background-color: grey; &:hover { background-color: white } } .tab { ... } .citation { ... }} All you have to do is# Header A introduces.button like this:

#header a {
  color: orange;
  #bundle > .button;
}
Copy the code

scope

Scopes in LESS are very similar to other programming languages in that they first look for variables or mixed modules locally, and if they are not found they go to the parent scope until they are found.#page {
  @var: white;
  #header {
    color: @var; // white
  }
}

#footer {
  color: @var; // red  
}
Copy the code

annotation

The CSS form of comments is still retained in LESS: /* Hello, I'm a csS-style comment */. Class {color: black} LESSm a silent comment, I won't show up in your CSS
.class { color: white }
Copy the code

Importing

You can import.less files with or without the.less suffix in the main file: @import"lib.less";
@import "lib"; If you want to import a CSS file and don't want LESS to process it, just use the.css suffix: @import"lib.css"; So LESS will skip it and not deal with it.Copy the code

String interpolation

Variables can be embedded in strings in a way similar to Ruby and PHP, with structures like @{name} : @base-URL:"http://assets.fnord.com";
background-image: url("@{base-url}/images/bg.png");
Copy the code

Avoid compilation

Sometimes we need to output incorrect CSS syntax or use some proprietary syntax that LESS doesn't know. To print such a value, precede the string with a ~, for example:.class {filter: ~"ms:alwaysHasItsOwnSyntax.For.Stuff()"; } we can use "contains the compiler will avoid value, the output is: class {filter: ms: alwaysHasItsOwnSyntax. For. Stuff (); }Copy the code

JavaScript expression

JavaScript expressions can also be used in.less files. This can be used in the back quotation: @var: '"hello".toUpperCase() + '! '`; Output: @ var:"HELLO!"; Note that you can also use string interpolation and avoid compiling: @str:"hello";
@var: ~`"@{str}".toUpperCase() + '! '`; Output: @var: HELLO! ; It can also access the JavaScript environment: @ height: ` document. The body. The clientHeight `; If you want to parse a JavaScript string into a hexadecimal color value, you can use the color function: @color: color(' windox.color.basecolor '); @darkcolor: darken(@color, 10%);Copy the code

LESS sites in other countries

English: http://lesscss.org (need to climb over the wall) Russian: http://lesscss.ru German:http://lesscss.de Japanese: http://less-ja.studiomohawk.com/ Belarus: http://www.designcontest.com/show/lesscss-be About Alexis Sellier - LESS author LESS Chinese website (abandoned) description: This page is intended to give the bootstrap-loving siege master a quick way to review the LessCss documentation. Since there is already a good translation from LESS China website (which is now obsolete), so I just plagiarized it, haha. We sincerely thank them for their contributions! powered by LESS and hiless Fork me on GitHubCopy the code