I am looking to do a for loop inside of Less. Is it possible to do this inside of Less? I know it has the capability to evaluate js but to this degree?
While CSS doesn't have loop structures, it does provide a counter() that you can increment based on any number of DOM-related conditions, and use in generated content. Sadly it can't be used outside the content property (yet), so our background-colors are not applied: HTML.
Yes, and recommended. It is a locally defined variable and sent as a return value. var sum_odd_numbers = function () { var sum = 0; for (var i = 1; i < 3000; i += 2) { sum += i; } return sum; } console.
Can I run two for loops in one statement in javascript? Would I do it like this? TL;DR: Yes, in the initializer and loop (not the condition) sections, with commas.
Approach 1: Using the for loop: The HTML elements can be iterated by using the regular JavaScript for loop. The number of elements to be iterated can be found using the length property. The for loop has three parts, initialization, condition expression, and increment/decrement expression.
I will recommend to checkout Twitter Bootsrap. They are building their grid system that way. They loop, with recursion, in a less mixin, instead of typing every class they need.
The interesting part is in mixins.less file, in the less directory, below "// The Grid" comment (line 516). The interesting portion is:
#grid {
.core (@gridColumnWidth, @gridGutterWidth) {
.spanX (@index) when (@index > 0) {
(~".span@{index}") { .span(@index); }
.spanX(@index - 1);
}
.spanX (0) {}
...
.span (@columns) {
width: (@gridColumnWidth * @columns) + (@gridGutterWidth * (@columns - 1));
}
...
Which is called in grid.less file in less directory this way:
#grid > .core(@gridColumnWidth, @gridGutterWidth);
Which produce (among other things):
.span12 {
width: 940px;
}
.span11 {
width: 860px;
}
.span10 {
width: 780px;
}
...
in bootstrap.css line 170.
For @gridColumnWidth, @gridGutterWidth and the rest of variables check variables.less file (line 184)
Be sure to have the last version of lessc node compiler installed.
There's nothing about loops in the docs, but since you can access JavaScript expressions via backticks, you could always define a function in your script (not your LESS code, but JavaScript — e.g., if in a browser, you'd have a separate script
element) that does your loop and then access it, e.g.:
@height: `doMyLoop()`
It depends on what you're trying to achieve with the loop. If you want the loop to output CSS rules, I suspect you're out of luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With