Using SASS for loop to define variable color

2019-09-08 04:51发布

问题:

So I have some colors defined like this:

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

Now I want to automatically create .blue_{number} classes for every color. So far I got:

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

But the ´color:$blue_#{$i}´ doesnt work. How can I reference to the variable in another way?! Im stuck.

回答1:

You can do something like this

Source for the function nth

SCSS

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

HTML

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

DEMO

See demo



回答2:

You can do this with a for loop, like this :

$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}
}

That code should returns something like :

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