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
[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]
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
[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]
Step 2
Create a LESS file in the same Nodejs folder as shown below.
style.less
[c]
h2{
color: #0000FF;
}
.cont(@count) when (@count > 0) {
.cont((@count - 1));
width: (30px * @count);
}
div {
.cont(10);
}
[/c]
Step 3
Compile the above less file in command prompt by using the following command.
[c]lessc style.less style.css[/c]
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]
Result
After making all the required changes, run the html file in a browser to get the following output.
Summary
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.