Reputation: 428
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 div
s 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;}
Upvotes: 4
Views: 5476
Reputation:
div {height: 5px;margin: 5px;}
div:nth-child(5n+1) {background: red;}
div:nth-child(5n+2) {background: blue;}
div:nth-child(5n+3) {background: green;}
div:nth-child(5n+4) {background: black;}
Upvotes: 3
Reputation: 3886
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.
Upvotes: 6
Reputation: 18137
The :nth-child() and :nth-of-type() pseudo-classes allows you to select elements with a formula.
1 row -> 1n blue
2 row -> 2n red
3 row -> 3n green
4 row -> 4n black
5 row -> empty (br is also an element)
6 row -> 3n green
7 row -> 1n blue
8 row -> 4n black
same logic till the end
Because of that the colors are different, try to use correct formula by n.
Edit: @worldofjr wrote you the correct formula for your case.
Upvotes: 2
Reputation: 874
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
Upvotes: 3
Reputation: 7122
You should use like this:-
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;}
Upvotes: 1