将第 n 个孩子中的 CSS 应用到第 n 个孩子

Mar*_*lla 3 css css-selectors

是否可以将样式添加到第 n 个孩子的第 n 个孩子?

我正在处理一份学生名单(15 名学生),其中前 5 名学生的名字会变成绿色,然后 6-10 是橙色,11-15 是红色。

就像将 CSS 应用于项目范围一样。

我找不到一些相关的问题。

希望你能理解我。

谢谢。

ol li:first-child{
  color: green;
}
ol li:nth-child(2), ol li:nth-child(3), ol li:nth-child(4), ol li:nth-child(5){
  color: green;
}
ol li:nth-child(6), ol li:nth-child(7), ol li:nth-child(8), ol li:nth-child(9), ol li:nth-child(10){
  color: orange;
}
ol li:nth-child(11), ol li:nth-child(12), ol li:nth-child(13), ol li:nth-child(14), ol li:nth-child(15){
  color: red;
}
Run Code Online (Sandbox Code Playgroud)
<ol>
  <li>student1</li>
  <li>student2</li>
  <li>student3</li>
  <li>student4</li>
  <li>student5</li>
  <li>student6</li>
  <li>student7</li>
  <li>student8</li>
  <li>student9</li>
  <li>student10</li>
  <li>student11</li>
  <li>student12</li>
  <li>student13</li>
  <li>student14</li>
  <li>student15</li>
</ol>
Run Code Online (Sandbox Code Playgroud)

Sag*_*dte 6

这就是你想要的?

在这第一个 css 中,由于否定,-n+5在元素之前选择前五个元素5th。如果删除负数,它将选择具有第 5 个元素的所有元素。因此再次n+11为元素 11 到 15添加。

.second如果您不想在第 15 个元素之后添加 css,则可以使用css。

.first p:nth-child(-n+5) {
  color: green;
}

.first p:nth-child(n + 5) {
  color: orange;
}

.first p:nth-child(n + 11) {
  color: red;
}

.second {
  margin-top: 50px;
}

.second p:nth-child(-n+5) {
  color: green;
}

.second p:nth-child(n + 6):nth-child(-n + 10) {
  color: orange;
}

.second p:nth-child(n + 11):nth-child(-n + 15) {
  color: red;
}
Run Code Online (Sandbox Code Playgroud)
<div class="first">
  <p>Student 1</p>
  <p>Student 2</p>
  <p>Student 3</p>
  <p>Student 4</p>
  <p>Student 5</p>
  <p>Student 6</p>
  <p>Student 7</p>
  <p>Student 8</p>
  <p>Student 9</p>
  <p>Student 10</p>
  <p>Student 11</p>
  <p>Student 12</p>
  <p>Student 13</p>
  <p>Student 14</p>
  <p>Student 15</p>
</div>

<div class="second">
  <p>Student 1</p>
  <p>Student 2</p>
  <p>Student 3</p>
  <p>Student 4</p>
  <p>Student 5</p>
  <p>Student 6</p>
  <p>Student 7</p>
  <p>Student 8</p>
  <p>Student 9</p>
  <p>Student 10</p>
  <p>Student 11</p>
  <p>Student 12</p>
  <p>Student 13</p>
  <p>Student 14</p>
  <p>Student 15</p>
  <p>Student 16</p>
  <p>Student 17</p>
</div>
Run Code Online (Sandbox Code Playgroud)