Less CSS - SPLessons

Chapter 22

Less Loops

Less Loops

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

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.

.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;
}

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

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

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

Below example demonstrates the use of Less Loops.
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.
Create a simple HTML file in Nodejs folder as shown below.

Less_loops.html

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

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);
}

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

lessc style.less style.css

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;
}

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

Summary

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

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