【问题标题】:cycling through a list of colors with sass使用 sass 在颜色列表中循环
【发布时间】:2013-03-06 09:14:35
【问题描述】:

可以列出三种颜色:

$color-list: x y z;

然后通过循环使用这三种颜色并将它们添加到无序列表项中。

我想要:

<li>row 1</li> (gets color x)
<li>row 2</li> (gets color y)
<li>row 3</li> (gets color z)
<li>row 4</li> (gets color x)

等等等等。

我曾尝试使用@each (http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#each-directive) 函数,但它只是在第一次通过列表后停止应用颜色。我希望颜色保持循环,直到列表项用完为止。

sass 可以做到这一点吗?

【问题讨论】:

  • 似乎是nth-child 的案例。 Sass 不知道你的标记。您可以使用@each 遍历列表项,但使用nth-child 会更灵活。

标签: loops sass each


【解决方案1】:

如果纯 CSS 可以,那么 Sass 也可以。这适用于任意数量的颜色:

http://codepen.io/cimmanon/pen/yoCDG

$colors: red, orange, yellow, green, blue, purple;

@for $i from 1 through length($colors) {
    li:nth-child(#{length($colors)}n+#{$i}) {
        background: nth($colors, $i)
    }
}

输出:

li:nth-child(6n+1) {
  background: red;
}

li:nth-child(6n+2) {
  background: orange;
}

li:nth-child(6n+3) {
  background: yellow;
}

li:nth-child(6n+4) {
  background: green;
}

li:nth-child(6n+5) {
  background: blue;
}

li:nth-child(6n+6) {
  background: purple;
}

【讨论】:

  • 我理解这种方法......但我想要的是它不断循环颜色。因此,在您的示例中,第 7 个 li 将从红色开始,并且会一直执行此操作,直到所有 li 元素都设置样式为止。
  • 确实如此?演示不是显示了吗?这就是6n+1 所做的:(6 * n) + 1 = 1、7、13、19、25 等。
  • 我编辑了我之前的评论。这很好用!我了解您现在的工作方式。
  • 这非常有效...我需要更改轮播项目的颜色,它完成了工作!但是有一个问题,如何让它随机?那将是最好的!
猜你喜欢
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多