Reputation: 23
is there any solution to generate even/odd rules for IE8 using LESS? I need to have separate rule for even and odd item in list. Something like this:
li.item:first-child {}
li.item:first-child + li {}
li.item:first-child + li + li {}
li.item:first-child + li + li + li {}
I decided to use LESS to generate this rules because i have to define more than 30 rules for it. This is my code that throws errors:
@iterations: 5;
@liaddon: ~" + li";
.li-loop (@i) when (@i > 0) {
li.item:first-child@{liaddon} * @i{}
.li-loop(@i - 1);
}
.li-loop(0) {};
.li-loop (@iterations);
Thanks for your help!
Upvotes: 2
Views: 315
Reputation: 23637
A simpler solution might be this mixin:
.li-loop (@i) when (@i > 0) {
& + li {
.li-loop(@i - 1);
& {
content: 'something'
}
}
}
Which you can call inside the selector you wish to expand:
li.item:first-child {
.li-loop (3);
}
This would generate the CSS below:
li.item:first-child + li {
content: 'something';
}
li.item:first-child + li + li {
content: 'something';
}
li.item:first-child + li + li + li {
content: 'something';
}
Another way to apply the same styles is to use :extend
:
.li-loop (@i) when (@i > 0) {
& + li {
.li-loop(@i - 1);
&:extend(li.item:first-child); // it will match this selector only
}
}
And add style properties in the same block where you call the mixin:
li.item:first-child {
.li-loop (3);
color: blue;
}
This generates the following CSS:
li.item:first-child,
li.item:first-child + li,
li.item:first-child + li + li,
li.item:first-child + li + li + li {
color: blue;
}
Update
If you need apply a different set of rules for each selector, then a loop is not the way to go. The best way using Less is to nest the selectors:
li.item:first-child {
color: black;
+ li {
color: red;
+ li {
color: green;
+ li {
color: yellow;
+ li {
color: orange;
}
}
}
}
}
Will generate the following CSS:
li.item:first-child {
color: black;
}
li.item:first-child + li {
color: red;
}
li.item:first-child + li + li {
color: green;
}
li.item:first-child + li + li + li {
color: yellow;
}
li.item:first-child + li + li + li + li {
color: orange;
}
Upvotes: 2
Reputation: 15609
This does not feel like the correct way to solve this problem. I think you are better creating an .even
class and an .odd
class with the differing styles. Then applying this to your markup.
Depending on the framework (MVC etc.) you are using this is relatively straight forward process. Worst case scenario you can use jQuery to apply the class names.
Upvotes: 2