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.
- 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.
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:
Now let’s write an HTML code to use the above CSS file.