在 CSS 中使用 nth-child 重复相同的颜色顺序?

Har*_*n K 4 html css css-selectors

演示: http: //jsfiddle.net/Nwf2A/57/

nth-child我在使用伪类显示颜色顺序时遇到问题。

第一组 4div以正确的顺序显示正确的颜色,但我希望第二组和第三组显示相同的颜色顺序。

下面是我的 HTML 和 CSS;

HTML:

<div> </div><div> </div><div> </div><div> </div>
<br>
<div> </div><div> </div><div> </div><div> </div>
<br>
<div> </div><div> </div><div> </div><div> </div>
Run Code Online (Sandbox Code Playgroud)

CSS:

div {height: 20px;margin: 5px;}
div:nth-child(1n) {background: blue;}
div:nth-child(2n) {background: red;}
div:nth-child(3n) {background: green;}
div:nth-child(4n) {background: black;}
Run Code Online (Sandbox Code Playgroud)

wor*_*fjr 6

以下 CSS 将为您提供所需的解决方案。

div {height: 20px;margin: 5px;}
div:nth-child(5n+1) {background: blue;}
div:nth-child(5n+2) {background: red;}
div:nth-child(5n+3) {background: green;}
div:nth-child(5n+4) {background: black;}
Run Code Online (Sandbox Code Playgroud)

<br>也是一个元素,因此您需要选择每 5 个元素 ( 5n) 以及每种颜色的偏移量(+1+2等)。

希望这可以帮助。