使用 :nth-child 循环遍历子 LI 元素

Bre*_*ett 4 css children sass css-selectors

好的,我有一种情况,我有一组颜色列表,比方说10

现在我想遍历子元素的颜色列表,并为它们指定 1-10 的颜色;但是我事先不知道我要生多少个孩子,所以我不确定如何处理。

就像,孩子 1 应该有颜色 1,但孩子 11 也应该有颜色 1(因为颜色列表重新开始),显然孩子 2 会得到颜色 2,孩子 12 会得到颜色 2,依此类推。 .

示例 HTML:

<ul>
    <li>Some Text</li> <!-- Color #1 -->
    <li>Some Text</li> 
    <li>Some Text</li>
    <li>Some Text</li>
    <li>Some Text</li>
    <li>Some Text</li>
    <li>Some Text</li>
    <li>Some Text</li>
    <li>Some Text</li>
    <li>Some Text</li> <!-- Color #10 -->

    <li>Some Text</li> <!-- Color #1 -->
    <li>Some Text</li>        
    <li>Some Text</li>
    <li>Some Text</li>
    <li>Some Text</li>
    <li>Some Text</li>
    <li>Some Text</li> <!-- Color #7 -->
</ul>
Run Code Online (Sandbox Code Playgroud)

无论如何,是否:nth-child可以使用 Sass 函数或其他方法来执行此操作?

Joh*_*nes 5

编辑/扩展答案

您可以使用.your_class:nth-child(10n+1), .your_class:nth-child(10n+2)etc. 作为选择器。“10”是“步长”:例如3n每三分之一,10n每十分之一。默认情况下计数从零开始,因此10n单独应用于第 10、20、30 等。“+1”是 1 的偏移量。

要从第一开始,请使用10n+1. 这将选择第 1 个、第 11 个、第 21 个等子项。

如果你写10n+2,这将选择第 2 个、第 12 个、第 22 个、第 32 个等子项

因此,您需要 10 个具有不同选择器的规则,从 开始10n+110n+2最多10n+10包含您要应用的不同设置。

下面是一个例子:

.container {
  width: 320px;
  height: auto;
  margin: 20px auto;
}
.x {
  float: left;
  width: 60px;
  height: 40px;
  text-align: center;
  line-height: 40px;
}
.x:nth-child(10n+1) {
  background: #ff0;
}
.x:nth-child(10n+2) {
  background: #af0;
}
.x:nth-child(10n+3) {
  background: #f0a;
}
.x:nth-child(10n+4) {
  background: #b5f;
}
.x:nth-child(10n+5) {
  background: #2f7;
}
.x:nth-child(10n+6) {
  background: #7df;
}
.x:nth-child(10n+7) {
  background: #4ac;
}
.x:nth-child(10n+8) {
  background: #73f;
}
.x:nth-child(10n+9) {
  background: #7cb;
}
.x:nth-child(10n+10) {
  background: #29f;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div class="x">1</div>
  <div class="x">2</div>
  <div class="x">3</div>
  <div class="x">4</div>
  <div class="x">5</div>
  <div class="x">6</div>
  <div class="x">7</div>
  <div class="x">8</div>
  <div class="x">9</div>
  <div class="x">10</div>
  <div class="x">11</div>
  <div class="x">12</div>
  <div class="x">13</div>
  <div class="x">14</div>
  <div class="x">15</div>
  <div class="x">16</div>
  <div class="x">17</div>
  <div class="x">18</div>
  <div class="x">19</div>
  <div class="x">20</div>
  <div class="x">21</div>
  <div class="x">22</div>
  <div class="x">23</div>
  <div class="x">24</div>
  <div class="x">25</div>
  <div class="x">26</div>
  <div class="x">27</div>
  <div class="x">28</div>
  <div class="x">29</div>
  <div class="x">30</div>
  <div class="x">31</div>
  <div class="x">32</div>
</div>
Run Code Online (Sandbox Code Playgroud)