Open In App

How to create a loop structure in LESS ?

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.

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



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




.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:




.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.




<!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:


Article Tags :