2017-01-11 23 views
1

分組序列與CSS:第n個孩子

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>

我需要什麼

  1. 紅色
  2. 綠色
  3. 藍色
  4. 黑色
  5. 紅色
  6. 綠色
  7. 藍色
  8. ...

...我怎麼用:nth-child實現這一目標?

回答

5

給出的nth-child語法

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

你需要使用4n+b

所以迭代,

背景red這將是4n+2如此,4x0+24x1+24x2+2等,這給你元素2,6,10

背景​​這將是4n+3所以,4x0+34x1+34x2+3等,它給你元件3,7,11

和用於背景'blue,這將是4n+4所以,4x0+44x1+44x2+4和等等,它給你的元素4,8,12

其餘元素1,5,9將彩色black默認給你的財產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>

+0

據我所知'[的#]'語法不被任何支持呢。 – Oriol

+0

@Oriol tbh我從[MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child)獲得了語法,但是在選擇器級別4中似乎是WD [link ](https://drafts.c​​sswg.org/selectors-4/#nth-child-pseudo) – dippas

+0

感謝您的解釋! – 3zzy

1

可以使用第n個孩子它,你需要有黑色指數1,5和9,可以處理4N + 1 紅色指標2如下

做, 6,10和它可以處理第i個4n + 2個

檢查這個片段

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>

希望它可以幫助