使用SASS for循环定义变量颜色



我已经定义了一些颜色:

$blue_1     : #ecf5f9;
$blue_2     : #cfe5ef;
$blue_3     : #b1d5e6;

现在我想为每个颜色自动创建。blue_{number}类。目前我得到:

@for $i from 1 through 12{
    .blue_#{$i}{
        color: $blue_#{$i};
    }   
}

但是' color:$blue_#{$i} '不起作用。我如何以另一种方式引用变量?!我困。

你可以这样做

函数nth的源代码

SCSS

$colors : #ecf5f9 #cfe5ef #b1d5e6;
@for $i from 1 through 3 {
  h1.blue-#{$i}
    {
      background-color : nth($colors, $i)  
     }
}

<h1 class="blue-1">blue one</h1>
<h1 class="blue-2">blue two</h1>
<h1 class="blue-3">blue three</h1>

看到演示

您可以使用for循环来实现这一点,如下所示:

$blue_1     : #ecf5f9;
$blue_2     : #cfe5ef;
$blue_3     : #b1d5e6;
@for $i from 1 through 9 {
    @if $i == 1 {
        $bg_color: $blue1
    }
    @if $i == 2 {
        $bg_color: $blue2
    }
    .....
    .blue#{$i} 
        background-color: #{!bg_color}
}

代码应该返回如下内容:

.blue1 {
  background-color:#ecf5f9;
}
.blue2 {
  background-color:#cfe5ef;
}

最新更新