Accessing an array key in SASS

前端 未结 4 1784
鱼传尺愫
鱼传尺愫 2020-12-05 00:43

I have a list in SASS, and I\'m trying to access on of the items by using bracket notation:

$collection[1];

but that gives me an error.

4条回答
  •  臣服心动
    2020-12-05 01:07

    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!

提交回复
热议问题