LESS Tutorial on LESS Loops

in this chapter, we will understand how loops work in less. loops statement allows us to execute a statement or group of statements multiple times. various iterative/loop structures can be created when recursive mixin combine with guard expressions and pattern matching.

example

the following example demonstrates the use of loops in the less file −

loop_example.htm

<!doctype html>
   <head>
      <link rel = "stylesheet" href = "style.css" type = "text/css" />
   </head>

   <body>
      <div class = "cont">
         <h2>welcome to tutorialspoint</h2>
         <p>the largest tutorials library on the web. </p>
      </div>
   </body>
</html>

next, create the style.less file.

style.less

.cont(@count) when (@count > 0) {
   .cont((@count - 1));
   width: (25px * @count);
}

div {
   .cont(7);
}

you can compile the style.less file to style.css by using the following command −

lessc style.less style.css

execute the above command; it will create the style.css file automatically with the following code −

style.css

div {
   width: 25px;
   width: 50px;
   width: 75px;
   width: 100px;
   width: 125px;
   width: 150px;
   width: 175px;
}

output

follow these steps to see how the above code works −

  • save the above html code in the loop_example.htm file.

  • open this html file in a browser, the following output will get displayed.

less css guard