MEMEPh. ideas that are worth sharing...

LESS Learn and Play

Foreword


We all know that HTML and CSS are not programming languages ​​but markup languages, so it is difficult to define variables, write methods, implement modular development, etc. like JS. In the current CSS writing mode, some public style class names are defined, and the corresponding style class name is added to which piece of HTML needs this style. Therefore, we often see that there are many style class names on a tag. In this mode, we should always pay attention to the priority of CSS to avoid overlapping styles...

 

In order to solve this dilemma of CSS, the idea of ​​CSS preprocessing and precompilation stands out, and the more representative ones are LESS, SASS, and Stylus. They add a lot of new syntax, writing methods, commonly used functions, etc. on the basis of traditional CSS, so that our CSS can become a programming language like JS. This article mainly introduces the syntax and use of LESS.

 

1. Compilation of LESS


The written LESS code cannot be run directly in the browser and needs to be compiled into normal CSS code. So let's first learn about the commonly used LESS compilation methods.

 

1. Call LESS.JS in the browser

LESS only supports running in modern browsers (latest versions of Chrome, Firefox, Safari and IE). We don't recommend using the LESS client in production because users will see loading delays when compiling LESS to CSS, and even a fraction of a second loading delay in the browser will degrade performance.

First introduce the LESS file where we set the style, note: rel='stylesheet/less' here

<link type="text/css" rel="stylesheet/less" href="1.less"/>

Then introduce the less.js file

<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/3.8.1/less.min.js" ></script>

There is an advantage to calling in the browser: the monitoring mode can be turned on, as long as our LESS changes, the browser will be recompiled within a certain period of time, and we can see the desired effect . The specific operations are as follows:

<script charset="utf-8" type="text/javascript">
//->Set a global variable less before introducing LESS, and configure some parameter values ​​(choose the items that need to be configured according to the situation)

var less = {
//->env: Set the running environment (production mode or development mode)
//production: The compiled CSS is cached in the local localStorage
//development: The compiled CSS is not cached locally. When the URL is not in a standard format (for example: file://...), it is automatically set to development

env: "development",
//->poll: In monitor mode, the time interval (ms) between each request

poll:500
} 

</script>

<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/3.8.1/less.min.js" ></script>
<script charset="utf-8" type="text/javascript">
//->Enable monitoring mode (env must be set to development)
less.watch();
</script>

It should be noted that since the browser uses ajax to pull the .less file, it will be opened directly in the local file system (that is, the address starts with file://) or if there is a cross-domain situation. The .less file cannot be obtained, so the style cannot take effect . Therefore, less is generally used for CSS preprocessing, and the method of referencing less is rarely used. Generally, after compiling less into CSS, the generated CSS file is referenced.

// index.html file

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>less</title>
<link type="text/css" rel="stylesheet/less" href="css/styles.less">
</head>
<body>
<header>
<p>Hello World!</p>
</header>

<script src="./less.min.js" type="text/javascript"></script>  

</body>

</html>

// styles.less file
@blue:#5B83AD;
@size:50px;
header {
color: @blue;
font-size: @size;
}

If the less file is imported directly, the following error will occur:

You can try to start the website with a simple web server, such as lite-server

npm install -g lite-server
lite-server //to run

 

2. Use the NODE command to compile LESS (single file)

This method is the most commonly used method in the current project and is suitable for the production environment of the project. It compiles our LESS file into a CSS file. We can directly import the CSS file into our project. The basic steps: install -> compile/ Compression and compilation -> or use NODE code to achieve batch compilation, etc.

Install the LESS module into the global NODE environment

npm install less -g

Compile with command

//-> Compile the styles.less file into a styles.css file (if there is no CSS file, it will be created by itself)
lessc styles.less styles.css

//->The compiled CSS file is compressed
lessc styles.less styles.min.css -x or --compress

Comparison before and after compiling the code through the node command:

// styles.less file (before compilation)
@blue:#5B83AD;
@size:50px;
header {
color: @blue;
font-size: @size;
}

// styles.css file (after compilation)
header {
color: #5B83AD;
font-size: 50px;
}

 

3. Write batch compiled code in NODE environment

When we compile with the NODE command above, we can only compile one file at a time. In this way, if there are multiple LESS in the page, each compilation is time-consuming. Therefore, we combine the NODE FS file read and write operations to write A set of batch compiled code.
   

//->Define the compiled file directory and target export directory
var dirPath = "./less/", tarPath = "./css/";

//->Import the modules that need to be used in NODE
var fs = require("fs"),
less = require("less");

//->Read all files in dirPath, check the type of files, only LESS files are stored
var ary = [],
files = fs.readdirSync(dirPath);
files.forEach(function (file, index) {
/\.(LESS)/i.test(file) ? ary.push(file) : null;
});

//->Compile all files in the directory and save the compiled results in the specified directory
ary.forEach(function (file) {
var newFile = file.replace(".less", ".css"),
conFile = fs.readFileSync(dirPath + file, "utf-8");
less.render(conFile, {compress: true}, function (error, output) {
fs.writeFileSync(tarPath + newFile, output.css, "utf-8");
});
});

 

4. Use tools to compile LESS

Currently commonly used compilation tools are: Koala (said to be the most popular), online compilation, SimpLESS, etc. This article does not do too much explanation.

 

2. The grammar of LESS


The basic grammar of LESS is basically divided into the following aspects: variables, mixins, nesting rules, operations, functions, scopes, etc.

 

1. Variables

The same as variables in JS, except that the variable definition of LESS uses @ instead of VAR .

//->LESS code
@link-color: #428bca;
@link-color-hover: darken(@link-color, 10%);

a {
color: @link-color;
&:hover {
color: @link-color-hover;
} 

} 

//->The result of compiling to CSS
a {
color: #428bca;
} 

a:hover {
color: #3071a9;
} 

In addition to using variables to store public property values ​​above, we can also use variables to store public URLs, selectors, etc. 

//->LESS code
.@{selector} {
width: 100px;
height: 100px;
@{property}: #000;
background: url("@{bgImg}/test.png");
} 

@selector: box;
@bgImg: "../img";
@property:color;

 

2. Mixins

① Basic use

Mixing can easily introduce a defined class A into another class B, so that class B can simply inherit all the properties of class A. We can also call with parameters, just like with functions.
   

//->LESS code
.public {
width: 100px;
height: 100px;
} 

nav ul {
.public;
list-style: none;
} 

//->The result of compiling to CSS
.public {
width: 100px;
height: 100px;
} 

nav ul {
width: 100px;
height: 100px;
list-style: none;
} 

In the above code, nav ul copies the style attribute value set in public to its own style. If you want to not output the result of public style in the compiled result, just write the following code:
   

//->LESS code
.public() {//->Add () after the selector to not compile this style
width: 100px;
height: 100px;
} 

nav ul {
.public;//If public has styles of descendant elements, it will also be copied over
list-style: none;
} 

//->The result of compiling to CSS
nav ul {
width: 100px;
height: 100px;
list-style: none;
} 

② extend

Although in the above case, nav ul inherits the styles in public, the principle is to copy the code, so that there will still be a lot of redundant CSS code in the compiled CSS. In order to avoid this, We can use the extend pseudo-class to implement style inheritance. Share a style with the original selector, but make sure that the original selector is not parenthesized.
 

//->LESS code
.public {
width: 100px;
height: 100px;
} 

nav ul {
  &:extend(.public);
list-style: none;
} 

//->The result of compiling to CSS
.public, nav ul {
width: 100px;
height: 100px;
} 

nav ul {
list-style: none;
} 

 

3. Nesting Rules

We can implement inheritance by nesting another selector in one selector, which greatly reduces the amount of code and makes the code look cleaner.

//->LESS code

#header {
color: black;
.navigation {
font-size: 12px;
}
.logo {
width: 300px;
&:hover { text-decoration: none }
}
}

//-> Result of compiling to CSS
#header { color: black; }
#header .navigation {
font-size: 12px;
}
#header .logo {
width: 300px;
}
#header .logo:hover {
text-decoration: none;
}

 

4. Functions & Operations

Operations provide addition, subtraction, multiplication, and division operations; we can perform operations on attribute values ​​and colors, so that complex relationships between attribute values ​​can be realized. The functions in LESS map JavaScript code one by one, and manipulate property values ​​if you wish.

Any number, color or variable can be involved in the calculation. Let's see a set of examples:

@base: 5%;
@filler: @base * 2;
@other: @base + @filler;
color: #888 / 4;
background-color: @base-color + #111;
height: 100% / 2 + @filler;

LESS provides a series of color operation functions. Colors are first converted to the 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

LESS provides a set of convenient mathematical functions that you can use to work with some numeric values:

round(1.67); // returns `2`
ceil(2.4);   // returns `3`
floor(2.6);  // returns `2`

 

5. Namespaces and scopes

The scope in LESS is very similar to other programming languages. First, the variable or mixed module will be searched locally. If it is not found, it will be searched in the parent scope until it is found.

@var: red;
#page {
  @var: white;
  #header {
    color: @var; // white
  }
}
#footer {
  color: @var; // red  
}