Open In App

How to create a loop structure in LESS ?

Improve
Improve
Like Article
Like
Save
Share
Report

Looping is a programming method that allows us to use a particular statement multiple times. LESS loops provide us with the same convenience. In LESS, loops are created using recursive mixin along with Guard Expressions and Pattern Matching. We have to follow the below steps for creating a loop in LESS.

  • The primary call to mixin: A primary call to mixin is required to start the iteration. Just like in other programming languages, we initialize the value of the looping variable to start the loop, similarly, this primary call acts as an initializer in LESS.
  • Mixin with guard expressions: Guard acts as a condition in the loop. It tells when the loop has to terminate.
  • Making mixin recursive: A statement is needed within the mixin to make it recursive. Just like other programming languages, an argument can be incremented or decremented when passed to the function for the next iteration.
  • Statements to be repeated: Then comes the statements that are needed to be repeated. Those statements are written inside the loop structure.

Let’s have a look at an example of a loop in LESS.

Example: We will write our LESS code with the loop.

file.less




.temp (@var) when (@var > 0) {
  .st-@{var} {
    font-size : (10px * @var);
  }
  .temp(@var - 1);
}
.temp(3);


This less code can be compiled into a CSS code by using the command:

lessc file.less file.css

CSS Output: This will generate the CSS code to the following equivalent:

file.css




.st-3 {
    font-size: 30px;
}
  
.st-2 {
    font-size: 20px;
}
  
.st-1 {
    font-size: 10px;
}


Now let’s write an HTML code to use the above CSS file.

index.html




<!DOCTYPE html>
<html>
  
<head>
    <link rel="stylesheet" 
        href="file.css" type="text/css" />
</head>
  
<body>
    <div>
        <h2 class="st-3">Welcome To GFG</h2>
        <p class="st-2">
            GeeksforGeeks is a platform
            for learning enthusiasts.
        </p>
  
        <p class="st-1">
            Computer Science Portal.
        </p>
    </div>
</body>
  
</html>


Output:



Last Updated : 20 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads