cssloopsstylus

Loops with variables in Stylus


I would like to make a mixin for button color. My goal is to iterate through a list of values (green, red, blue) and then build the class names and then apply the correct variable color to the background.

I have managed to get this far:

green = #38ab0b
red = #ab130b
blue = #099aab

colors = green, red, blue

for color, i in colors
  .btn-{color}
    background: mix(color, white, 60%)
    &:hover
      background: lookup(color)

However that renders out as:

.btn-color {
  background: ;
}
.btn-color:hover {
  background: #008000;
}
.btn-color {
  background: ;
}
.btn-color:hover {
  background: #f00;
}
.btn-color {
  background: ;
}
.btn-color:hover {
  background: #00f;
}

This example is similar to what I am wanting to do except it doesn't require variables is there a way I can achieve what I am wanting, I know how to do it in SCSS but I am trying to make the switch.

EDIT:

I have tried the following but can't get it to work either. The background is fine but the class name is not generating.

$green = #38ab0b
$red = #ab130b

colors = green $green, red $red

for pair in colors
  .btn-{pair[0]}
    background: pair[1]

Solution

  • Your example doesn't work because green, red and blue are already colors (nodes with rgba values). To fix it you can use strings as keys in the list:

    $green = #38ab0b
    $red = #ab130b
    
    colors = 'green' $green, 'red' $red
    
    for pair in colors
      .btn-{pair[0]}
        background: pair[1]
    

    Also you can use hashes (much better way for this task):

    colors = {
      green: #38ab0b
      red: #ab130b
      blue: #099aab
    }
    
    for name, color in colors
      .btn-{name}
        background: mix(color, white, 60%)
        &:hover
          background: color