SASS - Increment a class and choose the next variable in a list

﹥>﹥吖頭↗ 提交于 2019-12-01 07:30:11

问题


I'm trying to get a setup going that will increment a class from 1 through 12 and set a background color based on a variable list (also of 12 variables).

I am close, but not getting what I'd hoped. This is my first foray into control directives in SASS, so please forgive my ignorance.

Currently, I'm getting the class incremented successfully. It's the part of choosing the incremented variable that I am missing out on.

@mixin colors {
        $colors: $orange, $blue, $lightBlue, $teal, $lightTeal, $green, $lightGreen, $darkOrange, $orange, $lightOrange, $yellow, $lightYellow;
        @each $color in $colors {
            background-color:#{$color};
        }       
    }

@for $i from 1 through 12 { 
    .block-#{$i} {
        span {
            @include colors;
        }
    }
}

This is outputting something like:

.block-10 span {
    background-color: #faa21b;
    background-color: #005ca8;
    background-color: #0079c3;
    background-color: #0088a8;
    background-color: #009386;
    background-color: #00a05e;
    background-color: #589c45;
    background-color: #d4772b;
    background-color: #faa21b;
    background-color: #f7971f;
    background-color: #f9cc2a;
    background-color: #f6ee32;
}

Ideally, I'd like to have one background-color declaration, not 12. I think this might be something simple I'm missing, though. Any insight would be appreciated!


回答1:


Something like this? (not sure why you're using a mixin):

$orange: #faa21b;
$blue: #005ca8;
$lightBlue: #0079c3;
$teal: #0088a8;
$lightTeal: #009386;
$green: #00a05e;
$lightGreen: #589c45;
$darkOrange: #d4772b;
$orange: #faa21b;
$lightOrange: #f7971f;
$yellow: #f9cc2a;
$lightYellow: #f6ee32;
$i: 1;

@each $color in $orange, $blue, $lightBlue, $teal, $lightTeal, $green, $lightGreen, $darkOrange, $orange, $lightOrange, $yellow, $lightYellow {
    .block-#{$i} {
        span {
            background-color:#{$color};
        }
    }
    $i: $i + 1;
}

Output:

.block-1 span {
  background-color: #faa21b; }

.block-2 span {
  background-color: #005ca8; }

.block-3 span {
  background-color: #0079c3; }

.block-4 span {
  background-color: #0088a8; }

.block-5 span {
  background-color: #009386; }

.block-6 span {
  background-color: #00a05e; }

.block-7 span {
  background-color: #589c45; }

.block-8 span {
  background-color: #d4772b; }

.block-9 span {
  background-color: #faa21b; }

.block-10 span {
  background-color: #f7971f; }

.block-11 span {
  background-color: #f9cc2a; }

.block-12 span {
  background-color: #f6ee32; }


来源:https://stackoverflow.com/questions/14695965/sass-increment-a-class-and-choose-the-next-variable-in-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!