Less CSS - SPLessons

Less Loops

Chapter 22

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

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

shape Result

div {
width: 5px;
width: 10px;
width: 15px;
width: 20px;
width: 25px;
width: 30px;

shape Example 2

Below example demonstrates the use of recursive loop to generate CSS grid classes.

.generate-columns(@n, @i: 1) when (@i =< @n) {
.column-@{i} {
width: (@i * 100% / @n);
.generate-columns(@n, (@i + 1));

shape Result

.column-1 {
width: 25%;
.column-2 {
width: 100%;

shape Example 3

Below example demonstrates the use of Less Loops.

shape Conceptual

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.


<link rel="stylesheet" href="style.css" type="text/css" />
<div class="cont">
<h2>LESS CSS Tutorials</h2>
<p>Less Loops is awesome.</p>

shape Step 2

Create a LESS file in the same Nodejs folder as shown below.


color: #0000FF;
.cont(@count) when (@count &gt; 0) {
.cont((@count - 1));
width: (30px * @count);
div {

shape Step 3

Compile the above less file in command prompt by using the following command.

lessc style.less style.css

shape Step 4

By compiling the above less file, it automatically generates the following CSS file.


h2 {
color: #0000FF;
div {
width: 30px;
width: 60px;
width: 90px;
width: 120px;
width: 150px;
width: 180px;
width: 210px;
width: 240px;
width: 270px;
width: 300px;

shape Result

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


shape Key Points

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

shape Programming

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