Less CSS - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Less Loops

Less Loops

shape Introduction

This chapter discusses about Less loops and its uses. Further, the main scheme of Less loops along with an example is presented.

shape Description

The various iterative/loop structures can be created by combining Pattern Matching and Guard Expressions in Less. Below snippet code demonstrates the main scheme of Less Loops.

shape Example 1

[c] .loop(@counter) when (@counter > 0) { .loop((@counter - 1)); // next iteration width: (5px * @counter); // code for each iteration } div { .loop(6); // launch the loop } [/c]

shape Result

[c] div { width: 5px; width: 10px; width: 15px; width: 20px; width: 25px; width: 30px; } [/c]

shape Example 2

Below example demonstrates the use of recursive loop to generate CSS grid classes. [c] .generate-columns(2); .generate-columns(@n, @i: 1) when (@i =< @n) { .column-@{i} { width: (@i * 100% / @n); } .generate-columns(@n, (@i + 1)); } [/c]

shape Result

[c] .column-1 { width: 25%; } .column-2 { width: 100%; } [/c]

shape Example 3

Below example demonstrates the use of Less Loops.

shape Conceptual figure

The below conceptual diagram represents the overall view of the example like creating .html and .less files in node js folder and compiling .less to .css.

shape Step 1

Create a simple HTML file in Nodejs folder as shown below. Less_loops.html [c] <html> <head> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <body> <div class="cont"> <h2>LESS CSS Tutorials</h2> <p>Less Loops is awesome.</p> </div> </body> </html> [/c]

shape Step 2

Create a LESS file in the same Nodejs folder as shown below. style.less [c] h2{ color: #0000FF; } .cont(@count) when (@count &gt; 0) { .cont((@count - 1)); width: (30px * @count); } div { .cont(10); } [/c]

shape Step 3

Compile the above less file in command prompt by using the following command. [c]lessc style.less style.css[/c]

shape Step 4

By compiling the above less file, it automatically generates the following CSS file. style.css [c] h2 { color: #0000FF; } div { width: 30px; width: 60px; width: 90px; width: 120px; width: 150px; width: 180px; width: 210px; width: 240px; width: 270px; width: 300px; } [/c]

shape Result

After making all the required changes, run the html file in a browser to get the following output.

Summary

shape Key Points

  • The Pattern matching and Guard expression are the two important things to create the Less loop.

shape Programming Tips

  • Make sure that both the HTML and LESS files are created in the same node js folder.
  • Check all the required changes in the coding before running the application.