less the Getting Started tutorial

Foreword

CSS short board

    As a front-end learners we more or less have to learn some CSS, as one of the three cornerstones of front-end development, always leading the tide to Web development. The CSS language as a marker, possibly for beginners first impression is easy to understand, there is no logic, unlike the program looks like. In the syntax updated whenever new properties made compliant browser will immediately become a stumbling block, it can be said CSS shortcomings can not be ignored.

    The birth of a problem is often accompanied by the rise of technology, the development of the Web in the past few years, in order to allow CSS and logical, short board is not so serious, the emergence of some magical pre-processing language. Let them become a completely CSS can use variables, loops, inheritance, methods from a variety of characteristics defined markup language, logic can be greatly enhanced.

Pre-birth language

Which as far as I know there are three languages: Sass, Less, Stylus.

  1. Sass was born in 2007, written in Ruby, its grammatical features are very comprehensive, it can be said entirely the CSS turned into a programming language. Also very popular at home and abroad, and its project team was very strong, is a very good pre-processing language.
  2. Stylus born in 2010, from the Node.js community, grammatical functions and Sass are not comparable, it is a very unique and innovative language.
  3. Less born in 2009, an open source project created by the impact of the Sass. It extends the CSS language, such as increased variable, mixed (mixin), functions and other features that make CSS easier to maintain, easy to make the theme of expansion ( quoted in the official website ).

Pre-selected language

This is a very tangled issue.

In my opinion, this is like looking for a girlfriend, virtuous people like the quiet, it was like a lively and playful, each have their own hobbies, can be closed at night after lights actually are similar, so you do not have too tangled. Of course, first you need to have a girlfriend.

Appears in the online discussion, Sass and Stylus Less compared to the more feature-rich, but for learning costs and time to adapt, Less slightly better, and this is the reason I chose the Less.

Less CSS does not remove any functionality, but in the existing grammar, add a lot of extra features, so learning Less is a very comfortable thing.

If you've had any contact with the pretreatment language, should learn what a tangled, it is better to look at the following Less introduction, I believe you will love it.

Use the prelude Less

There are two ways to use Less

  1. Less.js introduced in the page 
    can be the official website to download
    or use CDN
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/2.7.2/less.min.js"></script>

Note that, the link tag must be introduced before Less.js, and the rel attribute of the link tag is set to stylesheet / less.

       <link rel="stylesheet/less" href="style.less"> <script src="less.min.js"></script>
  1. Npm install using the command line
npm install -g less

Specific use the command

$ lessc styles.less > styles.css

If there are problems, the official website has a clear step.

If you are a user of Webpack, also need to be treated with the less-loader, concrete and tangible my article: Webpack Flight Manual , which details the handling of less.

If you are in a local environment, you can use the first approach is very simple; but in a production environment, performance is very important, it is best to use the second way.

text

Now I will introduce the features Less.

variable

We often see the same value is repeated many times in the CSS, so the difficulty in code maintenance.
Ideally, this should be the following:

const bgColor="skyblue";
$(".post-content").css("background-color",bgColor);
$("#wrap").css("background-color",bgColor); $(".arctive").css("background-color",bgColor);

As long as we modify  bgColorit a variable, the entire page background color will change.

The Less variables in a very powerful, of all things, it is worth mentioning that it is a constant variable, it can only be defined once and can not be reused.
Value of the variable

      /* Less */
      @color: #999;
      @bgColor: skyblue;//不要添加引号 @width: 50%; #wrap { color: @color; width: @width; } /* 生成后的 CSS */ #wrap { color: #999; width: 50%; }

At  the beginning of the definition of variables and typed directly use  the name. @@

In peacetime work, we can put frequently used variables encapsulated into a file so the code is conducive to the maintenance organization.

      @lightPrimaryColor: #c5cae9;
      @textPrimaryColor: #fff;
      @accentColor: rgb(99, 137, 185); @primaryTextColor: #646464; @secondaryTextColor: #000; @dividerColor: #b6b6b6; @borderColor: #dadada;

Select variables

Let selector into a dynamic

      /* Less */
      @mySelector: #wrap;
      @Wrap: wrap;
      @{mySelector}{ //变量名 必须使用大括号包裹
        color: #999;
        width: 50%; } .@{Wrap}{ color:#ccc; } #@{Wrap}{ color:#666; } /* 生成的 CSS */ #wrap{ color: #999; width: 50%; } .wrap{ color:#ccc; } #wrap{ color:#666; }

Property variable

Reduce the amount of code can be written

      /* Less */
      @borderStyle: border-style;
      @Soild:solid;
      #wrap{
        @{borderStyle}: @Soild;//变量名 必须使用大括号包裹 } /* 生成的 CSS */ #wrap{ border-style:solid; } 

url variable

When the project structure change, modify its variable.

      /* Less */
      @images: "../img";//需要加引号
      body {
        background: url("@{images}/dog.png");//变量名 必须使用大括号包裹 } /* 生成的 CSS */ body { background: url("../img/dog.png"); } 

Declare variables

Somewhat similar mix of the following methods

      - 结构: @name: { 属性: 值 ;};
      - 使用:@name();
      /* Less */
      @background: {background:red;};
 #main{ @background(); } @Rules:{ width: 200px; height: 200px; border: solid 1px red; };  #con{ @Rules(); } /* 生成的 CSS */  #main{ background:red; }  #con{ width: 200px; height: 200px; border: solid 1px red; }

Variable operation

We must mention, Less variable operation completely beyond my expectations, very strong.

  - 加减法时 以第一个数据的单位为基准
  - 乘除法时 注意单位一定要统一
      /* Less */
      @width:300px;
      @color:#222;  #wrap{ width:@width-20; height:@width-20*5; margin:(@width-20)*5; color:@color*2; background-color:@color + #111; } /* 生成的 CSS */  #wrap{ width:280px; height:200px; margin:1400px; color:#444; background-color:#333; } 

Variable Scope

Word understanding is: the principle of proximity , not to mention me closure.

With Demo official website

      /* Less */
      @var: @a;
      @a: 100%; #wrap { width: @var; @a: 9%; } /* 生成的 CSS */ #wrap { width: 9%; }

With variables to define variables

      /* Less */
      @fnord:  "I am fnord.";
      @var:    "fnord";
      #wrap::after{ content: @@var; //将@var替换为其值 content:@fnord; } /* 生成的 CSS */ #wrap::after{ content: "I am fnord."; }

Nesting

& Magical

&: One selector on behalf of the name, this case is header.

      /* Less */
      #header{
        &:after{
          content:"Less is more!";
        }
        .title{
          font-weight:bold;
        }
        &_content{//理解方式:直接把 & 替换成 #header
          margin:20px; } } /* 生成的 CSS */ #header::after{ content:"Less is more!"; } #header .title{ //嵌套了 font-weight:bold; } #header_content{//没有嵌套! margin:20px; }

Media Inquiries

In previous work, we use media queries, must write a separate element

      #wrap{
        width:500px;
      }
      @media screen and (max-width:768px){ #wrap{ width:100px; } }

Less provides a very convenient way

      /* Less */
      #main{
          //something...
    
          @media screen{
              @media (max-width:768px){ width:100px; } } @media tv { width:2000px; } } /* 生成的 CSS */ @media screen and (maxwidth:768px){ #main{ width:100px; } } @media tv{ #main{ width:2000px; } }

The only drawback is that each element will compile their own  @media statement, and will not be merged.

Combat skills

Less can make use of the elements, to define your own private style.

      /* Less */
      #main{
        // something..
        &.show{
          display:block;
        }
      }
      .show{
        display:none;
      }
      const main = document.getElementById("main");
      main.classList.add("show");

result:

      #main.show{
        display:block;
      }
      .show{ display:none; //会被覆盖。 }

Hybrid approach

Non-parametric methods

Methods like the declaration of a collection, simply type the name to use.

      /* Less */
      .card { // 等价于 .card()
          background: #f6f6f6;
          -webkit-box-shadow: 0 1px 2px rgba(151, 151, 151, .58); box-shadow: 0 1px 2px rgba(151, 151, 151, .58); } #wrap{ .card;//等价于.card(); } /* 生成的 CSS */ #wrap{ background: #f6f6f6; -webkit-box-shadow: 0 1px 2px rgba(151, 151, 151, .58); box-shadow: 0 1px 2px rgba(151, 151, 151, .58); }

Wherein  .card the  .card() equivalent.
Personal recommendations, in order to avoid confusion the code should be written as:

      .card(){
        //something...
      }
      #wrap{
        .card();
      }
要点:
  `.` 与 `#` 皆可作为 方法前缀。
  方法后写不写 `()` 看个人习惯。

The default parameter method

Less can use the default parameters, if the parameter is not passed, then the default parameters.

@arguments Like the JS  arguments refer to all of the parameters.

Parameters must pass with the unit.

      /* Less */
      .border(@a:10px,@b:50px,@c:30px,@color:#000){ border:solid 1px @color; box-shadow: @arguments;//指代的是 全部参数 } #main{ .border(0px,5px,30px,red);//必须带着单位 } #wrap{ .border(0px); } #content{ .border;//等价于 .border() } /* 生成的 CSS */ #main{ border:solid 1px red; box-shadow:0px,5px,30px,red; } #wrap{ border:solid 1px #000; box-shadow: 0px 50px 30px #000; } #content{ border:solid 1px #000; box-shadow: 10px 50px 30px #000; } 

Pattern matching method

Object-oriented multi-state very similar

      /* Less */
      .triangle(top,@width:20px,@color:#000){ border-color:transparent transparent @color transparent ; } .triangle(right,@width:20px,@color:#000){ border-color:transparent @color transparent transparent ; } .triangle(bottom,@width:20px,@color:#000){ border-color:@color transparent transparent transparent ; } .triangle(left,@width:20px,@color:#000){ border-color:transparent transparent transparent @color; } .triangle(@_,@width:20px,@color:#000){ border-style: solid; border-width: @width; } #main{ .triangle(left, 50px, #999) } /* 生成的 CSS */ #main{ border-color:transparent transparent transparent #999; border-style: solid; border-width: 50px; }

Points

  - 第一个参数 `left` 要会找到方法中匹配程度最高的,如果匹配程度相同,将全部选择,并存在着样式覆盖替换。

  - 如果匹配的参数 是变量,则将会匹配,如 `@_` 。

Namespace method

So that more standardized method

      /* Less */
      #card(){
          background: #723232; .d(@w:300px){ width: @w;  #a(@h:300px){ height: @h;//可以使用上一层传进来的方法 width: @w; } } }  #wrap{  #card > .d > #a(100px); // 父元素不能加 括号 }  #main{  #card .d(); }  #con{ //不得单独使用命名空间的方法 //.d() 如果前面没有引入命名空间 #card ,将会报错  #card; // 等价于 #card(); .d(20px); //必须先引入 #card } /* 生成的 CSS */  #wrap{ height:100px; width:300px; }  #main{ width:300px; }  #con{ width:20px; } 

Points

  - 在 CSS 中`>` 选择器,选择的是 儿子元素,就是 必须与父元素 有直接血源的元素。
  - 在引入命令空间时,如使用 `>` 选择器,父元素不能加 括号。
  - 不得单独使用命名空间的方法 必须先引入命名空间,才能使用 其中方法。
  - 子方法 可以使用上一层传进来的方法

Conditions of screening methods

Less no if else, but it has when

    /* Less */
    #card{
        
        // and 运算符 ,相当于 与运算 &&,必须条件全部符合才会执行
        .border(@width,@color,@style) when (@width>100px) and(@color=#999){ border:@style @color @width; } // not 运算符,相当于 非运算 !,条件为 不符合才会执行 .background(@color) when not (@color>=#222){ background:@color; } // , 逗号分隔符:相当于 或运算 ||,只要有一个符合条件就会执行 .font(@size:20px) when (@size>50px) , (@size<100px){ font-size: @size; } } #main{ #card>.border(200px,#999,solid); #card .background(#111); #card > .font(40px); } /* 生成后的 CSS */ #main{ border:solid #999 200px; background:#111; font-size:40px; }

Points

  - 比较运算有: > >= = =< <。
  - = 代表的是等于
  - 除去关键字 true 以外的值都被视为 false:

Variable number of arguments

If you want your method to accept indefinite number of parameters, you can use ... as if ES6 expansion operator.

      /* Less */
      .boxShadow(...){
          box-shadow: @arguments;
      }
      .textShadow(@a,...){
          text-shadow: @arguments;
      }
      #main{
          .boxShadow(1px,4px,30px,red); .textShadow(1px,4px,30px,red); } /* 生成后的 CSS */ #main{ box-shadow: 1px 4px 30px red; text-shadow: 1px 4px 30px red; }

Method important!

Very simple to use, after the method name with keywords.

      /* Less */
      .border{
          border: solid 1px red; margin: 50px; }  #main{ .border() !important; } /* 生成后的 CSS */  #main { border: solid 1px red !important; margin: 50px !important; }

Cycle method

Less does not provide for circulation, but also beat clever programmers, using recursion to achieve.

The following is a Demo official network, generating simulated grid system.

      /* Less */
      .generate-columns(4);
    
      .generate-columns(@n, @i: 1) when (@i =< @n) { .column-@{i} { width: (@i * 100% / @n); } .generate-columns(@n, (@i + 1)); } /* 生成后的 CSS */ .column-1 { width: 25%; } .column-2 { width: 50%; } .column-3 { width: 75%; } .column-4 { width: 100%; }
  1. Properties splicing method

+_ It represents a space; + represents a comma.


  - 逗号
      /* Less */
      .boxShadow() {
          box-shadow+: inset 0 0 10px #555; } .main { .boxShadow(); box-shadow+: 0 0 20px black; } /* 生成后的 CSS */ .main { box-shadow: inset 0 0 10px #555, 0 0 20px black; }
- 空格
      /* Less */
      .Animation() {
        transform+_: scale(2);
      }
      .main {
        .Animation();
        transform+_: rotate(15deg); } /* 生成的 CSS */ .main {  transform: scale(2) rotate(15deg); }
  1. Combat skills

    Here is the official website of a very praise Demo

      /* Less */
      .average(@x, @y) {
        @average: ((@x + @y) / 2); } div { .average(16px, 50px); // 调用 方法 padding: @average; // 使用返回值 } /* 生成的 CSS */ div { padding: 33px; }

Less can be said to be an elegant programming language.

inherit

Less extend is a pseudo class. It inheritable all style declarations in the match.
extend the use of keywords

      /* Less */
      .animation{
          transition: all .3s ease-out;
          .hide{
            transform:scale(0);
          }
      }
      #main{ &:extend(.animation); } #con{ &:extend(.animation .hide); } /* 生成后的 CSS */ .animation,#main{ transition: all .3s ease-out; } .animation .hide , #con{ transform:scale(0); }

all global search and replace

使用选择器匹配到的 全部声明。
      /* Less */
      #main{
        width: 200px;
      }
      #main {
        &:after {
          content:"Less is good!"; } } #wrap:extend(#main all) {} /* 生成的 CSS */ #main,#wrap{ width: 200px; } #main:after, #wrap:after { content: "Less is good!"; }

Reduce repetitive code

On the surface, the biggest difference and extend the method is extend the same selectors share the same declarations, and the method is to use your own statement, it will increase the repeatability of the code.

The method compared with the above example extend:

      /* Less */
      .Method{
        width: 200px; &:after { content:"Less is good!"; } }  #main{ .Method; }  #wrap{ .Method; } /* 生成的 CSS */  #main{ width: 200px; &:after{ content:"Less is good!"; }  }  #wrap{ width: 200px; &:after{ content:"Less is good!"; }  } 

Points

Translation official website

    • Between the selector and the extension spaces are allowed: pre: hover: extend (div pre).
    • You can have multiple extensions: pre: hover: extend (div pre): extend (.bucket tr) - Note that this is pre: hover: extend (div pre, .bucket tr) the same.
    • This is not possible, it must be extended at the end: pre: hover: extend (div pre) .nth-child (odd).
  • If a rule set contains a plurality of selectors, all selectors can extend the use of keywords.

    Importing

    1. Less import file suffixes may be omitted

      import "main"; 
      //等价于
      import "main.less";
    2. @import Position and can be positioned

      #main{
        font-size:15px;
      }
      @import "style";
  1. reference

    Less of the most powerful features of
    using the introduction of Less files, but it will not compile.

    /* Less */
    @import (reference) "bootstrap.less"; 
    
    #wrap:extend(.navbar all){}
     翻译官网:
     > 使用@import (reference)导入外部文件,但不会添加 把导入的文件 编译到最终输出中,只引用。
    
  2. once

    The default behavior @import statement. This indicates that the same file will be imported once, and repeat the code then import the file will not be resolved.
    @import (once) "foo.less";
    @import (once) "foo.less"; // this statement will be ignored
  3. multiple

    Use @import (multiple) allows the import files of the same name.
    /* Less */
       
    // file: foo.less
    .a {
      color: green;
    }
    // file: main.less
    @import (multiple) "foo.less"; @import (multiple) "foo.less"; /* 生成后的 CSS */ .a { color: green; } .a { color: green; }

function

  1. Determine the type

    • isnumber

      判断给定的值 是否 是一个数字。
      
      ```less
      isnumber(#ff0);     // false
      isnumber(blue);     // false isnumber("string"); // false isnumber(1234); // true isnumber(56px); // true isnumber(7.8%); // true isnumber(keyword); // false isnumber(url(...)); // false ``` 
    • iscolor

      > 判断给定的值 是否 是一个颜色。
      
    • isurl

      > 判断给定的值 是否 是一个 url 。
      
  2. Color manipulation

    • saturate

      > 增加一定数值的颜色饱和度。
      
    • lighten

      > 增加一定数值的颜色亮度。
      
    • darken

      > 降低一定数值的颜色亮度。
      
    • fade

      > 给颜色设定一定数值的透明度。
      
    • mix

      > 根据比例混合两种颜色。
      
  3. Mathematical Functions

    • ceil

      > 向上取整。
      
    • floor

      > 向下取整。
      
    • percentage

      > 将浮点数转换为百分比字符串。
      
    • round

      > 四舍五入。
      
    • sqrt

      > 计算一个数的平方根。
      
    • abs

      > 计算数字的绝对值,原样保持单位。
      
    • pow

      > 计算一个数的乘方。
      

Due to the limited length of the article, you can only introduce the use of high efficiency function.

If you want to know more, you can go to the official web link function

other

  1. Note

    • / * * / CSS native annotations, are compiled in the CSS file.
    • / / Annotator Less provide will not be compiled in the CSS file.
  2. Avoid compilation
      /* Less */
      #main{
        width:~'calc(300px-30px)';
      }
    
      /* 生成后的 CSS */ #main{ width:calc(300px-30px); }
  结构: `~' 值 '`
  1. Use JS

    Because Less is written by JS, so there is a unique characteristic Less: code uses Javascript.

      /* Less */
      @content:`"aaa".toUpperCase()`;
      #randomColor{
        @randomColor: ~"rgb(`Math.round(Math.random() * 256)`,`Math.round(Math.random() * 256)`,`Math.round(Math.random() * 256)`)";
      }
      #wrap{ width: ~"`Math.round(Math.random() * 100)`px"; &:after{ content:@content; } height: ~"`window.innerHeight`px"; alert:~"`alert(1)`"; #randomColor(); background-color: @randomColor; } /* 生成后的 CSS */ // 弹出 1 #wrap{ width: 随机值(0~100)px; height: 743px;//由电脑而异 background: 随机颜色; } #wrap::after{ content:"AAA"; }

    A few months ago, there is a  CSS in JS concept very fire, and now it seems  JS in CSS have never not.
I think that it can be made in accordance with wheels Less this feature, JS to control CSS, forming a dynamic property, if successful, is likely to change the front end of the current open position.

Guess you like

Origin www.cnblogs.com/moumoon/p/11100365.html