Less cycle

Time:2020-12-1

In this section, we will learn the loop in less. Loops should be very common in programming languages. There are loops in general programming languages, such as in JavaScriptforCirculationwhileHowever, there are no such two kinds of syntax in less, but they are used to realize the loop through its own call.

The use of recycling

In less, the hybrid can call itself. When a hybrid recursively calls itself, combined with the two features of guard expression and pattern matching, the loop structure can be written out.

Example:

For example, the loop outputs fourpaddingProperties:

.loop(@i) when (@i > 0) {
   . loop ((@ I - 1)); // recursively calls itself
   padding: (10px + 5 * @i); 
 }
 
.call{
   . loop (4); // call loop
}

Compile to CSS code:

.call {
  padding: 15px;
  padding: 20px;
  padding: 25px;
  padding: 30px;
}

Let’s analyze the above less code:

  • First of all, look at the first line. It’s a mixture with conditional judgment, which I learned earlier..loopWith one parameter@iWhen the conditions are met@i > 0You can execute the code in curly braces.
  • then.loop((@i - 1))Represents the call mix itself, and subtracts one from the parameter value. This step will be executed as long as the condition is satisfied, until@i > 0
  • In the end.callCall in.loop, give the parameter@iAssignment, because the requirement is to loop out four timespaddingAttribute, so you can give@iThe parameter is assigned a value of 4.

Create multiple style classes through loops

The most common use of recursive loops is to generate CSS for grid systems.

Example:
.xkd(@n, @i: 1) when (@i =< @n) {
  [email protected]{i} {
    width: (@i * 100% / @n);
  }
  .xkd(@n, (@i + 1));
}

.xkd(5);

Compile to CSS code:

.grid1 {
  width: 20%;
}
.grid2 {
  width: 40%;
}
.grid3 {
  width: 60%;
}
.grid4 {
  width: 80%;
}
.grid5 {
  width: 100%;
}

In the above code,.xkdThere are five cycles, and one is created each time[email protected]{i}Style class.

Sometimes, in the actual project, we often put the font, color, margin and other styles as public styles in a public file, and then define the styles of some columns, such as font size, 12px, 14px, 16px, and so on. It will be troublesome to write one by one

.font(@i) when(@i <= 28){
   [email protected]{i} {
      font-size: @i + 0px ;
   }
   .font((@i + 2));
}
   
.font(12);

Compile to CSS code:

f12 {
  font-size: 12px;
}
f14 {
  font-size: 14px;
}
f16 {
  font-size: 16px;
}
f18 {
  font-size: 18px;
}
f20 {
  font-size: 20px;
}
f22 {
  font-size: 22px;
}
f24 {
  font-size: 24px;
}
f26 {
  font-size: 26px;
}
f28 {
  font-size: 28px;
}

summary

In this section, we mainly learn about the loop in less, which is very common in programming languages. We can reduce the amount of code through the loop. Sometimes large sections of similar code can be implemented by looping a few lines of code.

Link:https://www.9xkd.com/