Reputation: 968
I am looking to target elements using nth-child, there are 3 colours (grey-1, grey-2 and grey-3).
On the fourth element, I want the colours to loop e.g.
What is the most efficient way of doing this, I have the option of using jQuery but would prefer using CSS3. The list maybe long, which is why I don't want to change the dom with .addClass().
Upvotes: 1
Views: 711
Reputation: 240928
The
:nth-child(an+b)
CSS pseudo-class matches an element that hasan+b-1
siblings before it in the document tree, for a given positive or zero value forn
, and has a parent element. More simply stated, the selector matches a number of child elements whose numeric position in the series of children matches the patternan+b
.
In order to select every third element, you would use :nth-child(3n)
. Increment b
accordingly in order to target all the elements :nth-child(3n+1)
, :nth-child(3n+2)
, :nth-child(3n+3)
:
div:nth-child(3n+1) {
background: #ccc;
}
div:nth-child(3n+2) {
background: #ddd;
}
div:nth-child(3n+3) {
background: #eee;
}
div {
height: 20px;
}
div:nth-child(3n+1) {
background: #ccc;
}
div:nth-child(3n+2) {
background: #ddd;
}
div:nth-child(3n+3) {
background: #eee;
}
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
Upvotes: 2
Reputation: 195992
Assuming that the elements are the direct children of a common container (for example li
children of a ul
), you can do
li:nth-child(3n+1) {
color: green
}
li:nth-child(3n+2) {
color: blue
}
li:nth-child(3n+3) {
color: red
}
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
</ul>
Upvotes: 1