Accessing an array key in SASS

$color-collection: ('red', 'orange', 'green', 'blue');

@for $i from 0 to length($color-collection) {
    .color-#{$i} {
        color: unquote(nth($color-collection, $i+1));
    }
}

Use nth(), also unquote() if you want to pass quoted strings.

Though, I personally wouldn't:

$color-collection: (red, rgba(50,50,80, .5), darken(green, 50%), rgba(blue, .5));

@for $i from 0 to length($color-collection) {
    .color-#{$i} {
        color: nth($color-collection, $i+1);
    }
}

Because then you can pass any color object.


You can use @each rule instead of @for, which is more semantic, faster, and it makes the code shorter:

$color-collection: (red, orange, green, blue);

@each $color in $color-collection {
    .color-#{$color} {
        color: $color;
    }
}

Or if you prefer you can use $color-collection list directly into the @each directive:

@each $color in red, orange, green, blue {
    .color-#{$color} {
        color: $color;
    }
}

As @bookcasey says is preferable to use unquoted strings because then you can pass any color object or function

Sass reference for @each directive


just came across this and tested bookcasey's answer, which works well but I wanted to use the color name as the class instead; I found that this code works as I needed.

$colors: ( 'black', 'white', 'red', 'green', 'blue' );

@for $i from 0 to length($colors) {
    $thisColor: unquote(nth($colors, $i+1));
    .color-#{$thisColor} {
        color: $thisColor;
    }
}

using the #{...} allows you to use functions as well, so if you need to use an arbitrary name that may not be used directly in the rules you could use

@for $i from 0 to length($colors) {
    .color-#{unquote(nth($colors, $i+1))} {
        // some rules that don't actually use the var
        // so there's no need to cache the var
    }
}

output:

.color-black { color: black; }
.color-white { color: white; }
.color-red { color: red; }
// etc..

Hope this helps someone else!

Tags:

Css

Sass