Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat the same color order using nth-child in CSS?

Demo: http://jsfiddle.net/Nwf2A/57/

I have a problem with the display of an order of colors using the nth-child pseudo-class.

The first set of 4 divs display the correct colors in the right order, but I want the second and third sets to display the same order of colors.

Below is my HTML and 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>

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;}
like image 264
Harikaran K Avatar asked Oct 18 '25 06:10

Harikaran K


2 Answers

The following CSS will give you the solution you require.

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;}

<br> is also an element, so you need to select every 5th element (5n) with an offset for each color (+1, +2, etc).

Hope this helps.

like image 79
worldofjr Avatar answered Oct 20 '25 20:10

worldofjr


div {height: 20px;margin: 5px;}
div:nth-of-type(4n) {background: blue;}
div:nth-of-type(4n+1) {background: red;}
div:nth-of-type(4n+2) {background: green;}
div:nth-of-type(4n+3) {background: black;}

change the nth-child to nth-of-type

working demo

like image 24
yugi Avatar answered Oct 20 '25 21:10

yugi