Accessing the name of the variable rather than its value

前端 未结 4 1186
遥遥无期
遥遥无期 2021-01-14 12:56

I am trying to write a loop that will cycle through colors and condense the amount of code in my scss file. Here is a simple example of what I have:

$color1:         


        
4条回答
  •  滥情空心
    2021-01-14 13:32

    You can't access the name of the variable directly, you'd have to store it as an additional value.

    Sass 3.2 and older (list of lists)

    Sass doesn't have mappings yet, so the next best thing is a list of lists.

    $color1: ('color1', blue);
    $color2: ('color2', red);
    $color3: ('color3', white);
    $color4: ('color4', black);
    
    @each $color in $color1, $color2, $color3, $color4 {
        $name: nth($color, 1);
        $value: nth($color, 2);
        .#{$name}-bg { background-color: $value; }
        .#{$name}-border { border-color: $value; }
    }
    

    Sass 3.3 and newer (mappings)

    Starting with 3.3, you have access to mappings. It's functionally the same as the list of lists, but syntactically more concise.

    $colors:
        ( 'color1': blue
        , 'color2': red
        , 'color3': white
        , 'color4': black
        );
    
    @each $name, $value in $colors {
        .#{$name}-bg { background-color: $value; }
        .#{$name}-border { border-color: $value; }
    }
    

    Alternately

    Or if your color names are really "color1", "color2", etc., you can also just construct the name on the fly rather than specifying them explicitly:

    $color1: blue;
    $color2: red;
    $color3: white;
    $color4: black;
    
    $num: 0;
    @each $color in ($color1, $color2, $color3, $color4) {
        $num: $num + 1;
        .color#{$num}-bg { background-color: $color; }
        .color#{$num}-border { border-color: $color; }
    }
    

提交回复
热议问题