ekfuhrmann - 9 months ago 37

Sass (Sass) Question

I'm looking for the best method in SASS to iterate a class's

`order`

`1`

`@for $i from 1 through 3 {`

&:nth-child(#{$i}) {

order: 3;

background: green;

}

}

@for $i from 4 through 6 {

&:nth-child(#{$i}) {

order: 1;

background: blue;

}

}

@for $i from 7 through 9 {

&:nth-child(#{$i}) {

order: 2;

background: red;

}

}

Full Example of Code Working on Codepen

Is there a better way to do this that I am missing?

Answer

This will do what you're asking with a single loop and some math. There's probably an even more efficient way, but this is what I could come up with:

```
.box {
@for $i from 0 through 9 {
$c : $i + 1;
&:nth-child(#{$c}) {
order: (($i - $i % 3) / 3) + 1;
}
}
}
```

**Outputs:**

```
.box:nth-child(1) { order: 1; }
.box:nth-child(2) { order: 1; }
.box:nth-child(3) { order: 1; }
.box:nth-child(4) { order: 2; }
.box:nth-child(5) { order: 2; }
.box:nth-child(6) { order: 2; }
.box:nth-child(7) { order: 3; }
.box:nth-child(8) { order: 3; }
.box:nth-child(9) { order: 3; }
.box:nth-child(10) { order: 4; }
```

Note that counter starts with zero, which is why I needed to use the $c variable. There might be a way around that but it was killing the groups of threes when I tried to get around it. You can change the ending variable in the loop (from 9) to whatever number you want and it will continue incrementing groups of 3.

**In Action:**

http://www.sassmeister.com/gist/6506fa7b74b2341539b1373d943cb9cc

Source (Stackoverflow)