正如@hopper 所说,主要问题是您没有在插值变量前面加上美元符号,因此他的答案应该被标记为正确,但我想添加一个提示。
对于这种特定情况,请使用@each规则而不是@for循环。原因:
- 你不需要知道列表的长度
- 您不需要使用
length()函数来计算列表的长度
- 您不需要使用 nth() 函数
@each规则比@for指令更语义化
编码:
$colours: rgb(255,255,255), // white
rgb(255,0,0), // red
rgb(135,206,250), // sky blue
rgb(255,255,0); // yellow
@each $colour in $colours {
#cp#{$colour} {
background-color: rgba($colour, 0.6);
&:hover {
background-color: rgba($colour, 1);
cursor: pointer;
}
}
}
或者,如果您愿意,可以在 @each 指令中包含每个 $colour 而不是声明 $colors 变量:
$colour1: rgb(255,255,255); // white
$colour2: rgb(255,0,0); // red
$colour3: rgb(135,206,250); // sky blue
$colour4: rgb(255,255,0); // yellow
@each $colour in $colour1, $colour2, $colour3, $colour4 {
#cp#{$colour} {
background-color: rgba($colour, 0.6);
&:hover {
background-color: rgba($colour, 1);
cursor: pointer;
}
}
}
@each指令的 Sass 参考