# Less Loops

#### Chapter 22

5 Steps - 3 Clicks

# Less Loops

### Introduction

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

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

### 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
}
```

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

### Example 2

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

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

### Result

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

### Example 3

Below example demonstrates the use of Less Loops.

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

### Step 1

Create a simple HTML file in Nodejs folder as shown below.

Less_loops.html

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

### Step 2

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

style.less

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

### Step 3

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

`lessc style.less style.css`

### Step 4

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

style.css

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

### Result

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

### Key Points

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

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