Using loops in LESS
So youre using LESS as your CSS preprocessor. One of the best things about LESS is that you can do loops and build classes dynamically.
Example:
I wanted to make classes to make divs a percentage of their container in increments of 10. I could have written 10 classes, but this is much nicer and easier to maintain.
.mixin-loop (@index) when (@index > 0) {
.per-@{index}0 {
display: inline-block;
width: @index * 10%;
}
.mixin-loop(@index - 1);
}
.mixin-loop (0) {}
.mixin-loop(10);
Outputs...
.per-100 {
display: inline-block;
width: 100%;
}
.per-90 {
display: inline-block;
width: 90%;
}
.per-80 {
display: inline-block;
width: 80%;
}
.per-70 {
display: inline-block;
width: 70%;
}
.per-60 {
display: inline-block;
width: 60%;
}
.per-50 {
display: inline-block;
width: 50%;
}
.per-40 {
display: inline-block;
width: 40%;
}
.per-30 {
display: inline-block;
width: 30%;
}
.per-20 {
display: inline-block;
width: 20%;
}
.per-10 {
display: inline-block;
width: 10%;
}
Happy pre-processing!
Written by David Morrow
Related protips
1 Response
how can we get strings in place of those numbers, can we have an array of strings and append them to the .per class in the above example ?
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Css
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#