Loops with variables in Stylus
I would like to make a mixin for a button color. My goal is to iterate over a list of values (green, red, blue) and then create class names and then apply the correct variable color to the background.
I 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, it stands 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 want to do, except that it doesn't require variables, there is a way I can achieve what I want, I know how to do it in SCSS, but I am trying to make a switch.
EDIT:
I've tried the following but can't get it to work. The background is fine, but no class name is generated.
$green = #38ab0b
$red = #ab130b
colors = green $green, red $red
for pair in colors
.btn-{pair[0]}
background: pair[1]
source to share
Your example doesn't work because green
, red
and blue
are already colors (nodes with rgba values). To fix this, you can use strings as keys in a 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
source to share