Blog archives

Getting the element index in a SASS @each loop

2 comments

I wonder why this isn’t in the default SASS documentation. If you want to iterate over a list in SASS using @each, how do you get the index of the current item? For example, to make odd-even colored table rows?


    $list: foo, bar, baz;

    @each $item in $list {
        .#{$item} {
            // Right, so we want to see if the item index is
            // odd or even, but how do we get the index?
        }
    }

Turns out this is not possible with @each, but you can use a combination of a @for loop and the little-used nth function:


    $list: foo, bar, baz;

    @for $i from 1 through length($list) {
        $item: nth($list, $i);

        .#{$item} {
            @if $i % 2 == 0 {
                background: red;
            } @else {
                background: blue;
            }
        }
    }

Note that lists in SASS start at 1, not at zero.

Add a comment

2 comments