Less CSS preprocessor

Table of contents

Install

note

nesting

variable

operate

Namespaces and accessors

Extend Extend 

Mixing Mixins

Pass the ruleset to the mixin 

function

Guards

import import 

escape character

merge

parent selector

Less usage 

Less plugin

programmatic use


Install

        Install lessc for global use:

Install Less on the server         via  NPM  (Node Package Manager)  :

npm install less -g

        You can also add a specific version after the package name. For example:  npm install [email protected] -g

        Install to project development

npm i less --save-dev

        This command will install the latest lessc official version to the project folder and add it to  the devDependencies of the project package.json  file

        Command line usage (command line usage):

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

        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

note

        Less , like CSS , supports two types of comments: multi-line comments and single-line comments. It's just that when compiling Less code, single-line comments don't show up in  CSS  files.

nesting

        Less nesting is a CSS  style with a hierarchical relationship  , and the CSS  hierarchy is  determined by the HTML  structure. Less nesting is used in selectors with descendant relationships and parent-child relationships, which can reduce the amount of code and make the code structure clearer.

.class1 {
  .class2 {
    .class3 {
      font-size: 30px;
      color:green;
    }
  }
}

variable

        Less uses the @ symbol to define variables, the syntax is: @ variable name: variable value . Variables can be used as interpolation, the syntax of variable interpolation is: " @{variable name} ".

        When used in style attribute values, variables can be used directly with @variable ; in other places, including selector names, attribute names, URLs  and  @import  statements, variables must be used in the form of interpolation.

@variable: 200px;         //定义变量作为样式属性值使用
@classname: .nav_a;       //变量值不可用中划线,此变量作为插值用于选择器名称

@{classname} {            //作为插值 必须加 “{}”
    width: @variable;     //作为属性值直接使用
}

        Variable scope: Variables will be searched from the local scope, and if they are not available, the compiler will search from the parent scope. Variables can be lazily loaded, allowing variables to be used even if they have not been declared.

operate

        Less  supports some arithmetic operations such as plus ( + ), minus ( - ), multiplication ( *  ) and division (  ), which can operate on any number, color or variable. 

@fontSize: 10px;              // 定义一个 Less 变量
.myclass {
 font-size: @fontSize * 2;    // 使用乘法(*)运算符操作变量 @fontSize
}  // 输出:.myclass { font-size: 20px; }

Namespaces and accessors

        Namespaces are used to group mixins under a common name. Using namespaces avoids name collisions and encapsulates  mixin  groups from the outside. Mixins can be accessed using the " > " symbol .

#myNamespace {
    .button () { 样式... }    // 在'#myNamespace'命名空间里面声明 mixin ('.button')
}
#header a {
    #myNamespace .button();
    #myNamespace > .button(); // 也可以使用 “>” 符号来访问 mixins ('.button')
}

Extend  Extend 

        Extend  is a  Less  pseudo-class that extends other selector styles within a selector by using " :extend( selector ) ". Extensions are placed in rulesets or appended to selectors. It is similar to a pseudo-class containing one or more classes, separated by commas.

.style:extend(.container, .img)
{
  background: #BF70A5;
}
.container {
  font-style: italic;
}
.img{
   font-size: 30px;
 }

// 输出
.style {
  background: #BF70A5;
}
.container,
.style {
  font-style: italic;
}
.img,
.style {
  font-size: 30px;
}

         Extensions cannot detect duplication of selectors.

.cont-main{
  font-size: 30px;
}
.cont-main{
  font-size: 30px;
}
.cont:extend(.cont-main, .cont-main) {}

// 输出
.cont-main,
.cont,
.cont {
  font-size: 30px;
}
.cont-main,
.cont,
.cont {
  font-size: 30px;
}

        The extended keyword " all  ", when the keyword " all " is identified in the extended parameter at the end , Less will expand all styles related to the extended parameter.

.style.nav,
.nav h3 {
  color: orange;
}
.nav {
  &:hover {
    color: green;
  }
}
.container:extend(.nav all) {} //扩展所有和 .nav 相关的样式

// 编译成css
.style.nav,
.nav h3,
.style.container,
.container h3 {
  color: orange;
}
.nav:hover,
.container:hover {
  color: green;
}

Mixing Mixins

        Mixins  are a set of  CSS  properties that allow you to use the properties of one class for another class. In  Less  , mixins  can be declared using class or id selectors and in the  same way as CSS  styles .

.p1{ color:red; }    // Mixins
.p2{ .p1; }
.p3{ .p1(); }

// 输出结果:
.p1 { color: red; }
.p2 { color: red; }
.p3 { color: red; }

        Mixins can take parameters like functions, and parameters can be separated by commas or semicolons. When commas and semicolons are used together, semicolons are used to separate each parameter and commas are used to separate CSS lists.

.box-shadow(@x: 0, @y: 0, @height: 3px, @width: 3px) { }
.myclass {
  .box-shadow(2px, 3px, 4px; 5px);// 传入两个参数,第一个参数为 2px,3px,4px,第二个参数为5px
}

        Do not export  Mixins : Mixins with " ( ) " will not be exported.

.a(){
  padding-left: 100px;
}
.myclass{
  .a;
}        // 最终CSS文件输出结果:.myclass {  padding-left: 100px; },.a不会输出

        Named parameters: Mixins provide parameter values ​​by using their names instead of positions. Parameters do not have any order of placing values, they can be referenced by name.

.mixin(@color: black; @fontSize: 10px) {
  color: @color;
  font-size: @fontSize;
}
.class1 {
  .mixin(@fontSize: 20px; @color: #F5A9D0);
}

        @arguments and @rest : @arguments includes all arguments passed when calling the Mixin  . Mixins  provide a variable number of arguments by using ... Assign parameters to variables by placing ... after the variable name ( @rest ) .

.mixin(@x; @rest...) {
    // 使用 ... 提供可变数量的参数
    // @rest 绑定剩余参数
    // @arguments 绑定的是所有参数,包括@x参数
}

Pattern matching: The behavior of a mixin          can  be changed by passing parameters  to the mixin  . If you set the value of @color-new to dark , it will display the result in a darker color because the Mixin  definition matches dark as the first parameter.

.mixin(dark; @color) {
  color: darken(@color, 15%);
}
.mixin(light; @color) {
  color: lighten(@color, 15%);
}
@color-new: dark;
.line {
  .mixin(@color-new; #FF0000);
}

        Variables in mixins   are available and visible in the caller's scope.

        Mixins work very similarly to functions, Mixins  can also be nested, can accept parameters and return values.

.padding(@x, @y) {
  @padding: ((@x + @y) / 2);    // @padding 会当做返回值
}
.myclass{
  .padding(80px, 120px);        // call to the mixin
  padding-left: @padding;
}

.outerMixin(@value) {           // 混合nestedMixin 会当做返回值
  .nestedMixin() {
    font-size: @value;
  }
}
.myclass {
  .outerMixin(30);
  .nestedMixin();
}

Pass the ruleset to the mixin 

A detached         ruleset is a set of CSS properties, nested rulesets, media declarations or anything else stored in a variable. You can include it into a ruleset or other structure, and all its properties will be copied there. You can also use it as a mixin parameter and pass any other variables around it.

// 声明 detached 规则集合
@detached-ruleset: { background: red; };

// 使用 detached 规则集合
.top { @detached-ruleset(); }    // 编译结果:.top { background: red; }

The parentheses behind the detached rule set are required         when calling , @detached-ruleset ;  such calls are invalid.

Useful when         you want to define a mixin that abstracts away a block of code in a media query or a class name that is not supported by the browser. Rulesets can pass rulesets to mixins , so the mixin  will wrap them. for example:

.desktop-and-old-ie(@rules) {
  @media screen and (min-width: 1200) { @rules(); }
  html.lt-ie9 &                       { @rules(); }
}

header {
  background-color: blue;

  .desktop-and-old-ie({
    background-color: red;
  });
}

         A detached rule set can use all variables and mixins wherever it is defined and called. In other words, both the defining and calling scopes are valid for it. If both scopes contain the same variable or mixin, the value in the declared scope takes precedence.

@detached-ruleset: {
  @msg:declareMsg;                     // 声明中定义的变量 @msg
  msg:@msg;
  caller-variable: @callerVariable;    // 这里变量是 undefined
  .callerMixin();                      // 这里混合是 undefined 
};

selector {
  @detached-ruleset();                 // 使用分离规则集合
  
  @msg:callerMsg;                      // 调用中定义的变量 @msg (将被忽略)

  // 需要在分离规则集合内定义变量和混合
  @callerVariable: value;
  .callerMixin() {
    color: red;
  }
}

// 编译结果:
selector {
  msg: declareMsg;
  caller-variable: value;
  color: red;
}

        The scope of the declarations defining the set of separation rules is independent. Copying a detached rule set from one variable to another cannot modify its scope. The ruleset doesn't get a new scope, it's just referenced there.

@detached-1: { scope-detached: @one @two; };
.one {
  @one: visible;    // 规则集合不能使用 visible
  .two {
    @detached-2: @detached-1; // 拷贝/重命名 规则集合 
    @two: msg;
  }
}

.usePlace {
  .one > .two(); 
  @detached-2();
}

// 编译结果:
NameError: variable @one is undefined

        Finally, a detached rule set can be obtained by being unlocked (imported) into its scope.

#space {
  .importer1() {
    @detached: { scope-detached: @variable; }; // 定义分离规则集合
  }
}

.importer2() {
  @variable: value;     // 解锁分离规则集合能使用这个变量
  #space > .importer1();// 解锁/导入分离规则集合
}

.usePlace {
  .importer2();         // 第二次解锁/导入分离规则集合
   @detached();
}

// 编译结果:
.usePlace {
  scope-detached: value;
}

function

        Less  maps JavaScript code with value manipulation and uses predefined functions to manipulate HTML elements in stylesheets. Less provides many functions for converting colors, manipulating strings, and doing arithmetic. .

@color: #FF8000;
@width:1.0;
.mycolor{
    color: @color;
    width: percentage(@width);    // 函数 percentage() 将浮点数转换为百分比字符串
}
// 编译结果:
.mycolor {
    color: #FF8000;
    width: 100%;
}

        For more types of functions, see the link below: Less function reference http://shouce.jb51.net/less/functions/index.htm

Guards

        Guards can be used to match simple values ​​or number of arguments on expressions, similar to if/else statements, but  Less uses  Guards  instead of if/else statements, and performs calculations to specify matches. Using the when keyword introduces a  guard sequence. Additionally, the default function can be used to make a  mixin  match dependent on other  mixin  matches, which you can then use to create  "conditional  mixins " similar to else   or default  statements ( if and  else constructs , respectively  ) :

.mixin (@a) when (@a > 0) { ...  }
.mixin (@a) when (default()) { ... } // matches only if first mixin does not, i.e. when @a <= 0

        Less includes five guarded comparison operators: < , > , <= , >=  and = . You can use the comparison operator ( = ) to compare numbers, strings, identifiers, etc., while the remaining operators can only be used with numbers.

.mixin (@a) when (@a >= 20px){
	color:red;
}

.myclass { .mixin(20px) } // 输出:.myclass { color: red; }

         Less logical operators use the keyword and , and use the not keyword to cancel the condition.

.mixin (@a) when not (@a< 20px) and not (@a > 50px){
	font-size: @a;
} 
.class1 { .mixin(30px) }// 输出:.class1 { font-size: 30px; }

        Less can use type checking built-ins to determine matching value types.

        Guards can be used in namespaces, mixins , css  selectors  .

@usedScope: global;
@usedMixin: use;
#namespace when (@usedScope = global) {        // 命名空间使用 Guards 
	.mixin (@color) when(@usedMixin = use) {   // mixin 使用 Guards 
      .cont when (@color = red) {              // CSS 样式使用 Guards 
        background-color: red;
        color: black;
      }
      .style when not (@color = red) {         // CSS 样式使用 Guards 
        background-color: blue;
        color: white;
      }
	}
}
p{
     #namespace .mixin(blue);
}

import import 

        In Less , external files can be imported through the @import directive.

        File extension: If you use .css extension then it will be treated as  CSS  , if no extension or any other extension then it will be treated as  Less  and will be imported.

@import "style";      // imports the style.less
@import "style.less"; // imports the style.less
@import "style.php";  // imports the style.php as a less file
@import "style.css";  // it will kept the statement as it is

        Import Options: The available keywords are as follows:

reference It uses a Less file as a reference and does not output it.
inline It enables you to copy CSS to the output without processing it.
less It will treat imported files as regular Less files, albeit possibly with other file extensions.
css It will treat imported files as regular CSS files, albeit possibly with other file extensions.
once It will only import the file once.
multiple It imports the file multiple times.
optional Even if it can't find a file to import, it will keep compiling.

        Multiple keywords are allowed in an  @import  statement, but the keywords must be separated by commas. for example:

@import (less, optional) "custom.css";

escape character

        Sometimes, when you need to introduce invalid  CSS  syntax or  characters that Less  cannot recognize, you need to use escape characters. At this point, you can add a ~ in front of the string , and put the string that needs to be escaped in " ". The format is: ~"anything" .

.weird-element {
  content: ~"some horrible but needed css hack";
} // 输出:.weird-element { content: some horrible but needed css hack; }

merge

        It is  a feature of Less  for adding property values. Currently only two types of merging are supported. Use the " + " flag to add attribute values ​​and separate the added values ​​with commas, use the " +_ " flag to add attribute values ​​and separate the added values ​​with spaces.

// 使用 “+” 标识
.class {
  box-shadow+: 5px 5px 5px grey;
  box-shadow+: 0 0 5px #f78181;
}    //结果为:.class { box-shadow: 5px 5px 5px grey, 0 0 5px #f78181; }

// 使用 “+_” 标识
.class {
  transform+_: scale(1);
  transform+_: rotate(2deg);
}    //结果为:.class { transform: scale(1) rotate(2deg); }

parent selector

The &  (ampersand) operator         can be used  to refer to a parent selector, and is very common in applications that modify class or pseudo-class selectors.

         will represent the nearest selector as well as all parent selectors, by using  the &  operator, it is possible to repeatedly refer to a parent selector without using its name.

.select {
  && {
    color: #81BEF7;
  }

  &, &_class1 {
    color: #A4A4A4;
  }
}

// 输出
.select.select {
  color: #81BEF7;
}
.select,
.select_class1 {
  color: #A4A4A4;
}

        Put  back, you can change the order of selectors, and bring the current selector to the parent.

.side{
  div&{
    color:cyan;
  }
}
// 输出
div.side {
  color: cyan;
}

        Combination explosion: When multiple selectors at the same level are separated by " , " and its children use multiple  in a row , such as  &+&  or  &-& , all possible combinations will be generated.

div,p{
  &+&{
    color:red;
  }
}
// 输出为
div + div,
div + p,
p + div,
p + p {
  color: red;
}

Less usage 

Less plugin

        To use a plugin in the command line , you first need to install the plugin. Take  the less-plugin-clean-css  plugin as an example:

npm install -g less-plugin-clean-css

        Then use the plugin through the Lessc command, the format is:

lessc --plugin=PLUGIN=OPTIONS

# 以 less-plugin-clean-css 插件为例
lessc --plugin=less-plugin-clean-css="advanced"

        If the plug-in name starts with " less-plugin ", you can use the shorthand notation, and take the  less-plugin-clean-css plug-in as an example:

lessc --clean-css="advanced"    

        Use plugins in code, take  less-plugin-clean-css as an example:

var LessPluginCleanCSS = require('less-plugin-clean-css'),
cleanCSSPlugin = new LessPluginCleanCSS({advanced: true});
less.render(lessString, { plugins: [cleanCSSPlugin] })
   .then(function(output) {
    },
    function(error) {
    }
);

        When using the plug-in in the browser,  the JavaScript file corresponding to the plug-in should be introduced before the less.js  script .

<script src="plugin.js"></script>
<script>
less = { 
    plugins: [plugin]
};
</script>  
<script src="less.min.js"></script>

programmatic use

        The entry point into less is  the less.render function, and the usage format is as follows:

less.render(lessInput, options)
    .then(function(output) {
        // output.css = string of css
        // output.map = string of sourcemap
        // output.imports = array of string filenames of the imports referenced
    },
    function(error) {
    });

// or...

less.render(lessInput, options, function(error, output) {})

        You can access logs by adding a listener, as shown in the following format:

less.logger.addListener({
    debug: function(msg) {
    },
    info: function(msg) {
    },
    warn: function(msg) {
    },
    error: function(msg) {
    }
});

Guess you like

Origin blog.csdn.net/weixin_42754922/article/details/123604463