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

时间:2017-01-11 23:57:50

标签: html css css3 css-selectors pseudo-class

SDL_QuitSubSystem(SDL_INIT_EVERYTHING)
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;
}

我需要什么

  1. 黑色
  2. red
  3. 绿色
  4. 蓝色
  5. 红色
  6. 绿色
  7. 蓝色
  8. ...
  9. ...如何使用<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 个答案:

答案 0 :(得分:6)

给出nth-child语法

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

您需要使用4n+b

进行迭代

所以,

对于背景red,它将是4n+24x0+24x1+24x2+2等等,它们为您提供了元素2,6,10

对于背景green,它将是4n+34x0+34x1+34x2+3等等,它们为您提供了元素3,7,11

对于背景'blue,它将是4n+44x0+44x1+44x2+4等等,它们为您提供了元素4,8 ,12

根据black

中的属性,默认情况下,剩余的元素1,5,9将会被li着色

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>

答案 1 :(得分:1)

您可以使用nth-child执行此操作

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

检查此代码段

&#13;
&#13;
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;
}
&#13;
<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>
&#13;
&#13;
&#13;

希望有所帮助