Writing Less loops
One of the advantages of writing less instead of CSS is that you can create loops instead of repeating the same code again and again. Here are some examples that can help you understand how less loops work.
/* number of iterations for the mixin */
@iterations: 3;
/* the mixin test if counter has reached 0 */
.mixin-simple-loop (@i) when (@i > 0) {
/* print a class with @i variable in the class name */
.margin_top_@{i}0{
margin-top:(@i*10px);
}
/* print another class */
.margin_bottom_@{i}0{
margin-bottom:(@i*10px);
}
/* the mixin calls itself while lowering the counter @i */
.mixin-simple-loop(@i - 1);
}
// call the mixin
.mixin-simple-loop(@iterations);
/*---- output CSS code will be ---- */
.margin_top_30 {
margin-top: 30px;
}
.margin_bottom_30 {
margin-bottom: 30px;
}
.margin_top_20 {
margin-top: 20px;
}
.margin_bottom_20 {
margin-bottom: 20px;
}
.margin_top_10 {
margin-top: 10px;
}
.margin_bottom_10 {
margin-bottom: 10px;
}
Now you can use css classes such as
margin_top_10
to .. margin_top_30
margin_bottom_10
to .. margin_bottom_30
in your html file.
Try it out using the online less tester and add your modification. Hit Ctrl+Enter to compile your less into CSS, don’t forget to delete the comments if you do.
Hope you found this useful, cheers!
Excellent work, a question:
How to do this?
.index_10 {
top: 1px;
}
.index_9 {
top: 2px;
}
.incex_8 {
top: 3px;
}
.index 7 {
top: 4px;
}
.index 6 {
top: 5px;
}
.index_5 {
top: 6PX;
}
.index_4 {
top: 7px;
}
.index_3 {
top: 8px;
}
.index_2 {
top: 9px;
}
.index_1 {
top: 10px;
}
Thanks for your help 🙂
Hi Daniel,
Thanks for your question!
index goes from 1 to 10
top goes from 10 to 1
use @i for one and 11-@i for the other like so:
@iterations: 10;
.mixin-simple-loop (@i) when (@i > 0) {
@class_end : (11 - @i);
.index_@{class_end}{
top:(@i*1px);
}
.mixin-simple-loop(@i - 1);
}
.mixin-simple-loop(@iterations);
Try it out with the online less tester I posted about:
http://www.lehelmatyus.com/288/online-less-tester
ctrl + enter -> to compile
Feel free to share my blog posts if you find them useful.
Cheers!