A CSS preprocessor is a program that generates the CSS code by using the defined preprocessor ruleset and facilitates reducing the overall complexity of CSS code. LESS is a CSS preprocessor that is a CSS backward-compatible language extension. Mixins in LESS, are a way to include a bunch of CSS properties from one ruleset to another i.e multiple times in the same file.
In this article, we will know the Mixins in LESS, along with understanding their implementation and usage through the example.
Recursive Mixins: Recursive mixin is used for repetitively calling the same function until the loop reaches the desired value during the program execution by using the divide and conquer logic.
Syntax:
.loop(@a) when (@a > 0) { .loop((@a - 1)); Table: (6 * @a); } Table of 6{ .loop(10); }
Example 1: This example, demonstrate the use of recursive mixins in Less. We are using a loop in the recursive mixin. With the help of recursion, we are printing the table of 6 in the CSS code.
index.html
<!doctype html> < head > < title >Mixin Guards</ title > < link rel = "stylesheet" href = "var.css" type = "text/css" /> </ head > < body >< br >< br > < h1 >< b >neveropen</ b ></ h1 > < h2 >Learning recursive mixins...</ h2 > </ body > </ html > |
rec.less
.loop(@a) when (@a > 0 ) { .loop((@a - 1 )); table: ( 6 * @a); } Table of 6 { .loop( 10 ); } h 1 { color : green ; } h 2 { color : black ; } |
Now, to compile the above LESS code to CSS code, run the following command:
lessc var.less var.css
The compiled CSS file comes to be:
var.css
var.css
Table of 6 { table: 6 ; table: 12 ; table: 18 ; table: 24 ; table: 30 ; table: 36 ; table: 42 ; table: 48 ; table: 54 ; table: 60 ; } h 1 { color : green ; } h 2 { color : black ; } |
Output:
Example 2: This example demonstrates the use of recursive mixins in less using a while loop. With the help of recursion, we are printing numbers from 10 to 1 in the CSS code.
index.html
<!doctype html> < head > < title >Mixin Guards</ title > < link rel = "stylesheet" href = "recursive.css" type = "text/css" /> </ head > < body >< br >< br > < h1 >< b >neveropen</ b ></ h1 > < h2 >Learning recursive mixins...</ h2 > </ body > </ html > |
recursive.less
.while(@a) when (@a > 0 ){ .while((@a - 1 )); Number: ( 11 - @a); } Hello neveropen { .while( 10 ); } @primary: green ; @ color : white ; @bg: black ; h 1 { color : @primary; text-align : center ; } h 2 { color : @color; text-align : center ; } body { background-color : @bg; } |
Now, to compile the above LESS code to CSS code, run the following command:
lessc recursive.less recursive.css
The compiled CSS file comes to be:
recursive. less
Hello neveropen { Number: 10 ; Number: 9 ; Number: 8 ; Number: 7 ; Number: 6 ; Number: 5 ; Number: 4 ; Number: 3 ; Number: 2 ; Number: 1 ; } h 1 { color : green ; text-align : center ; } h 2 { color : white ; text-align : center ; } body { background-color : black ; } |
Output:
Reference: https://lesscss.org/features/#mixins-feature-loops-feature