Reputation: 1853
So I have a list of elements and I want them to style accordingly.
As you can see here in the image above I have 4 different colors and if added another element I would expect the color will be red. But am not sure how to do it.
I can't make :nth-child(1n)
and so on because obviously it will take the other element using that code. I know I can just use :first-child
but how can apply these colors in the next 4 elements and so on?
To make it clearer of what I wanted to achieve you can refer to this image:
Upvotes: 0
Views: 352
Reputation: 273
Since you have to repeat after 4 elements, use 4n
in the nth-child
selector.
li:nth-child(4n+1) {
color: blue;
}
li:nth-child(4n+2) {
color: green;
}
li:nth-child(4n+3) {
color: pink;
}
li:nth-child(4n+4) {
color: red;
}
Upvotes: 1
Reputation: 15838
The formula for nth-child
is an+b
, so you can have a color for nth-child(4n)
(+0), another for nth-child(4n+1)
, for nth-child(4n+2)
and for nth-child(4n+3)
https://www.w3schools.com/cssref/tryit.asp?filename=trycss3_nth-child_formula
Upvotes: 1