This is the fifth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021.

Hello everyone, I am zhang Three years old 🤣, a French front-end ⚖️. Love share 🖋️, love ice ice 🧊🧊. Welcome friends to add my wechat: Maomaoibingbing, pull you into the group, discuss together, look forward to growing with you 🥂.

preface

When we write CSS, we can encounter a lot of problems. Now we can use CSS preprocessor to improve our development efficiency and development of comfort, this article will take you to talk about the more popular characteristics of Less and use methods.

A list,

1. CSS preprocessor

CSS preprocessor is a program that allows you to generate CSS using the preprocessor’s own unique syntax. There are many CSS preprocessors to choose from, and most CSS preprocessors add some features that native CSS does not have, such as code mixing, nested selectors, inheritance selectors, etc. These features make CSS structures more readable and maintainable. – the MDN Web Docs

2. Less

Less (short for Leaner Style Sheets) is a backward-compatible CSS extension language. Here is the official document of Less (Chinese version), which contains the Less language and the JavaScript developed les.js tool for converting Less styles to CSS styles. — Less Chinese

Two, start to use

1. Use it in the Node.js environment

1.1 Manual Compilation

Install Less globally:

npm i -g less
# or
yarn global add less

#Check the version. If the version exists, the installation is successful
lessc -v
#Lessc 4.1.2 (Less Compiler) [JavaScript]
Copy the code

After the global installation is successful, you can use the command line.less file to compile to.css file. Let’s give it a try and create a new demo. Less file.

@color-theme: #0094ff;

.demo {
    background-color: @color-theme;
}
Copy the code

Open the cli, switch to the directory of the demo file, and enter lessc demo.less demo. CSS to obtain the compiled file demo.css:

.demo {
  background-color: #0094ff;
}
Copy the code

1.2 Used in Webpack

Basic steps:

  1. The installationlessAs well asless-loader
  2. configurationwebpack
  3. If it is.vueThe file instyleAdd attributes to the taglang="less"

Installation:

npm i less less-loader --save-dev
# or
yarn add less less-loader --dev
Copy the code

Webpack configuration:

// webpack.config.js
module.exports = {
  module: {
    rules: [{test: /\.less$/i,
        loader: [
          // compiles Less to CSS
          'style-loader'.'css-loader'.'less-loader',],},],},};Copy the code

Attached is the WebPack configuration document portal: less-loader

Add the lang attribute to the style tag if it is a vue.js project:

<style lang="less" scoped>
// ...
</style>
Copy the code

2. Use it in the browser environment

In the head tag of the.html file:

<head>
    <! -- add less -->
    <link rel="stylesheet/less" type="text/css" href="./index.less" />
    <! -- Introducing less. Js core library -->
    <script src="/ / cdnjs.cloudflare.com/ajax/libs/less.js/3.11.1/less.min.js"></script>
</head>
Copy the code

Three, usage,

1. The variable

1.1 Definition and Usage

We can define variables using the @ sign at the beginning, and be careful to add a semicolon at the end.

@width: 10px;
@height: @width + 10px;

#header {
    width: @width;
    height: @height;
}
Copy the code

Compiled code:

#header {
    width: 10px;
    height: 20px;
}
Copy the code

In real development, we can name variables according to different types, which is not only easy to understand, but also easy to maintain.

/* ============ distance ============ */
@space-large: 36px;
@space-middle: 24px;
@space-small: 12px;
// ...

/* ============ color ============ */
// Color is the most defined variable in a project and can be split into a less file for maintenance
@color-theme: #0094ff;
@title-color: # 090909;
// ...
Copy the code

1.2 escape

When defining a variable, you can use any string that is output as is.

// Define the variable as a string
@min-1024: ~"(min-width: 1024px)";

.element {

    // Use this variable in the media query
    @media @min-1024 {
        color: skyblue; }}Copy the code

Compiled code:

@media (min-width: 1024px) {
  .element {
    color: skyblue; }}Copy the code

1.3 scope

Similar to the block-level scope in JavaScript, there is scope for variables in Less. That is, finite reads variables from the nearest scope, in other words, if there are two variables with the same name, then who and who uses the line near takes effect.

// define a variable with the same name @color-title
.demo {
    @color-title: pink;

    .item {
        @color-title: skyblue;

        .title {
            color: @color-title; // skyblue}}}Copy the code

Compiled code:

.demo .item .title {
  color: skyblue;
}
Copy the code

1.4 mapping

As of version 3.5, we can define a set of mapping values to improve the reusability of Less code. Just like the key/value pairs of Object in JavaScript, there can be multiple pairs without interfering with each other.

// before
// Define multiple variables
@color-theme: #0094ff;
@color-success: #93dd00;

.status {
    color: @color-theme;

    &.success {
        color: @color-success; }}// after
// Define a mapping
#colors() {
    theme: #0094ff;
    success: #93dd00;
}

.status {
    color: #colors[theme];

    &.success {
        color: #colors[success]; }}Copy the code

Compiled code:

.status {
  color: #0094ff;
}

.status.success {
  color: #93dd00;
}
Copy the code

2.

Mixins, or mixins, are a means of reusing code. You can easily put a block of code under one class name into another. Let’s take a look at the basics:

// An unpretentious class name
.bordered {
    border-top: solid 1px # 000;
}

#menu a {
    color: # 000;
    // Mix in code from the class name bordered, not forgetting the closing semicolon
    .bordered(a);// it could be.bordered;
}
Copy the code

Compiled code:

.bordered {
  border-top: solid 1px # 000;
}

#menu a {
  color: # 000;
  border-top: solid 1px # 000;
}
Copy the code

In real development, we can define public class names in global public style files and import and use them in the private style files of other components.

// src/styles/index.less
// Global style file

// Some public class names...
.mg-0-auto {
    margin: 0 auto ! important;
}

.text-center {
    text-align: center ! important;
}
Copy the code
// src/pages/Demo/index.less
// A component private style

@import url(@/styles/index.less); // Introduce global common styles

// A custom class name
.demo {
    background-color: #fff;
    // Use blending, and don't forget the closing semicolon
    .mg-0-auto(a);.text-center(a); }Copy the code

3. The nested

3.1 Using nesting

Less allows hierarchical class names/selectors to be nested, wrapped in curly braces.

.demo {
    margin: 0 auto;

    .box {
        display: flex;

        .item {
            color: # 000; }}}Copy the code

Compiled code:

.demo {
  margin: 0 auto;
}

.demo .box {
  display: flex;
}

.demo .box .item {
  color: # 000;
}
Copy the code

3.2 sign&

Use ampersand instead of parent element.

// before
.box {
    display: flex;

    .item {
        color: # 000;
    }

    .item.active {
        color: skyblue; }}// after
.box {
    display: flex;

    .item {
        color: # 000;

        // "&" replaces the parent class name ".item"
        &.active {
            color: skyblue; }}}Copy the code

3.3 @ Rule nesting and bubbling

@ rules (such as @media or @supports) can be nested in the same way as selectors. The @ rule is placed first, and the relative order of other elements in the same rule set remains the same. It’s called bubbling.

.component {
    width: 300px;

    @media (min-width: 768px) {
        width: 600px;

        @media (min-resolution: 192dpi) {
            background-color: skyblue; }}@media (min-width: 1280px) {
        width: 800px; }}Copy the code

Compiled code:

.component {
  width: 300px;
}

@media (min-width: 768px) {
  .component {
    width: 600px; }}@media (min-width: 768px) and (min-resolution: 192dpi) {
  .component {
    background-color: skyblue; }}@media (min-width: 1280px) {
  .component {
    width: 800px; }}Copy the code

The fly in the ointment is that each class name will compile a separate @media, and multiple media queries with the same condition will not be merged.

4. Operation

The arithmetic operators +, -, *, and/can operate on any number, color, or variable. If possible, arithmetic operators perform unit conversions before adding, subtracting, or comparing.

// All operands are converted to the same unit
@conversion-1: 5cm + 10mm; // The result is 6cm
@conversion-2: 2 - 3cm - 5mm; // The result is -1.5cm
@incompatible-units: 2 + 5px - 3cm; // The result is 4px
@base: 10%;
@filler: @base * 2; // The result is 20%
@other: @base + @filler; // The result is 30%
Copy the code

5. The function

Less has built-in functions for converting colors, manipulating strings, arithmetic operations, and more. Below is a list of some commonly used functions. For the complete version, please refer to the “Less Function Manual” on the official website.

  • Logic function
    • If returns different results depending on the expression
    • Boolean stores a Boolean value for if judgment
  • String function
    • Escape applies the URL encoding to special characters in the input string
    • Replace Replaces the text in a string
  • Mathematical function
    • Ceil rounds up to the next highest integer
    • Floor rounds down to the next smallest integer
    • Percentage Converts a floating point number to a percentage string
    • SQRT computes the square root of a number. Keep the units the same
    • Abs calculates the absolute value of a number. Keep the units the same
    • Min returns the minimum of one or more values
    • Max returns the maximum value of one or more values

6. Comment

We can use single-line comments and multi-line comments in less, where line comments are not compiled into CSS.

// Common comments are not compiled into CSS

/* Multi-line comments are compiled into CSS */
Copy the code

Compiled code:

/* Multi-line comments are compiled into CSS */
Copy the code

7. The import

We can import other LESS files in one less file, and then use the variables and mappings that have been imported. Import is usually done at the top of a LESS file.

// Can be introduced like this
@import url(a.less);

// Or introduce it like this
@import 'b.less';

// You can also import CSS files
@import 'style.css';
Copy the code

The resources

  • Less Chinese
  • webpack
  • MDN Web Docs
  • Learn Less- Just read this one