使用CSS分组序列:nth-​​child

[英]Grouped sequence with CSS :nth-child


ul,li {
  display: block;
  margin:0;
  padding:0;
  list-style:none;
}
li {
  background: black;
  color: white;
  padding: 10px;
}
li:nth-child(2n+2) {
  background: red;
}
li:nth-child(3n+3) {
  background: green;
}
li:nth-child(4n+4) {
  background: blue;
}
<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
  <li>four</li>
  <li>five</li>
  <li>six</li>
  <li>seven</li>
  <li>eight</li>
  <li>nine</li>
  <li>ten</li>
  <li>eleven</li>
  <li>twelve</li>
</ul>

What I need:

我需要的:

  1. black
  2. red
  3. green
  4. blue
  5. black
  6. red
  7. green
  8. blue
  9. ...

... how do I achieve this with :nth-child?

...我如何通过以下方式实现这一目标:nth-​​child?

2 个解决方案

#1


6  

given the nth-child syntax

给出了nth-child语法

:nth-child( <an-plus-b>  )

you need to iterate using 4n+b

你需要使用4n + b进行迭代

So,

for background red it will be 4n+2 so, 4x0+2, 4x1+2, 4x2+2 and so on, which gives you elements 2, 6, 10

对于背景红色它将是4n + 2所以,4x0 + 2,4x1 + 2,4x2 + 2等等,这给你元素2,6,10

for background green it will be 4n+3 so, 4x0+3, 4x1+3, 4x2+3 and so on, which gives you elements 3, 7, 11

对于背景绿色它将是4n + 3所以,4x0 + 3,4x1 + 3,4x2 + 3等等,这给你元素3,7,11

and for background'blue, it will be 4n+4 so, 4x0+4, 4x1+4, 4x2+4 and so on, which gives you elements 4, 8, 12

而对于background'blue,它将是4n + 4 so,4x0 + 4,4x1 + 4,4x2 + 4等等,它们为你提供了元素4,8,12

The remaining elements 1, 5, 9 will be colored black by default given your property in li

鉴于li中的属性,剩余的元素1,5,9将默认为黑色

ul,li {
  display: block;
  margin:0;
  padding:0;
  list-style:none;
}
li {
  background: black;
  color: white;
  padding: 10px;
}
li:nth-child(4n+2) {
  background: red;
}
li:nth-child(4n+3) {
  background: green;
}
li:nth-child(4n+4) {
  background: blue;
}
<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
  <li>four</li>
  <li>five</li>
  <li>six</li>
  <li>seven</li>
  <li>eight</li>
  <li>nine</li>
  <li>ten</li>
  <li>eleven</li>
  <li>twelve</li>
</ul>

#2


1  

You can do it using nth-child as follows

您可以使用nth-child执行此操作,如下所示

As you need to have black for indices 1,5 and 9 it can be dealt with 4n+1 red for indices 2,6,10 and it can be dealt ith 4n+2

由于你需要为指数1,5和9设置黑色,因此对于指数2,6,10可以处理4n + 1红色,并且可以处理4n + 2

check this snippet

检查这个片段

ul,
li {
  display: block;
  margin: 0;
  padding: 0;
  list-style: none;
}
li {
  background: black;
  color: white;
  padding: 10px;
}
li:nth-child(4n+1) {
  background: black;
}
li:nth-child(4n+2) {
  background: red;
}
li:nth-child(4n+3) {
  background: green;
}
li:nth-child(4n+4) {
  background: blue;
}
<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
  <li>four</li>
  <li>five</li>
  <li>six</li>
  <li>seven</li>
  <li>eight</li>
  <li>nine</li>
  <li>ten</li>
  <li>eleven</li>
  <li>twelve</li>
</ul>

Hope it helps

希望能帮助到你


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2017/01/11/608a62891b091e4ea9133a7080f3e891.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号