Alvaro
Alvaro

Reputation: 9662

for loop in stylus for CSS selector name

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)

Upvotes: 5

Views: 972

Answers (2)

kizu
kizu

Reputation: 43224

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.

Upvotes: 4

serraosays
serraosays

Reputation: 7849

You're overthinking this is a bit. Give all the elements the same class of .post and then use nth-child in CSS:

// For the 2,5,8 series
.post:nth-child(3n+2) {
  left: 0%;
}

// For the 1,4,7 series
.post:nth-child(3n+1) {
  left: 33.3%;
}

// For the 3,6,9 series
.post:nth-child(3) {
  left: 66.66%;
}

Upvotes: 0

Related Questions