Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop in stylus for CSS selector name

Tags:

stylus

Im using stylus and Im looking for a function to obtain the following result:

.post_1,.post_4,.post_7,.post_10,.post_13,.post_16,.post_19,.post_22 {
    left:0%;
}
.post_2,.post_5,.post_8,.post_11,.post_14,.post_17,.post_20,.post_23 {
    left:33.33%;
}
.post_3,.post_6,.post_9,.post_12,.post_15,.post_18,.post_21,.post_24 {
    left:66.66%;
}

This is my attempt

post_class(a,b)
    for i in (0..a - 1)
        for u in (1..b)
            .post_{a * u + i - (a - 1)}
                left floor(i*(100/a)%,2)

post_class(3,8)// 3 columns, 8 rows

Which gives my desired CSS but with all selectors with the same attribute (left with its value, in this case) separated.

.post_1 {left: 0%;}
.post_4 {left: 0%;}
.post_7 {left: 0%;}
.post_10 {left: 0%;}
.post_13 {left: 0%;}
.post_16 {left: 0%;}
.post_19 {left: 0%;}
.post_22 {left: 0%;}
.post_2 {left: 33.33%;}
.post_5 {left: 33.33%;}
.post_8 {left: 33.33%;}
.post_11 {left: 33.33%;}
.post_14 {left: 33.33%;}
.post_17 {left: 33.33%;}
.post_20 {left: 33.33%;}
.post_23 {left: 33.33%;}
.post_3 {left: 66.66%;}
.post_6 {left: 66.66%;}
.post_9 {left: 66.66%;}
.post_12 {left: 66.66%;}
.post_15 {left: 66.66%;}
.post_18 {left: 66.66%;}
.post_21 {left: 66.66%;}
.post_24 {left: 66.66%;}

I can only think of looping the names of the selectors, which I tried with no luck (throws error). Is it possible to achieve what Im looking for? (To clarify, I am looking for a way to simplify the resultant CSS)

like image 949
Alvaro Avatar asked Sep 25 '22 21:09

Alvaro


1 Answers

You can use a +cache mixin in your case:

post_class(a,b)
    for i in (0..a - 1)// 3 columns
        for u in (1..b)
            .post_{a * u + i - (a - 1)}
                $left = floor(i*(100/a)%,2)
                +cache($left)
                  left: $left

post_class(3,8)

This would join the selectors you'd like as it would generate a class for each new value, and then for each repeating value it would just @expand the existing class instead of writing a new one.

Note how you pass the key that you'd like the +cache to based on, so you'd need to store it at first, so you could reuse it both in the cache call and later in the left declaration.

like image 186
kizu Avatar answered Oct 12 '22 08:10

kizu