Best css-selectors questions in August 2010

Select every Nth element in CSS

9 votes

Is it possible to select, say, every fourth element in a set of elements?

Ex: I have 16 <div> elements... I could write something like.

div:nth-child(4),
div:nth-child(8),
div:nth-child(12),
div:nth-child(16)

is there a better way to do this?

Well, it's called nth-child(), so use the n variable and work with it (you can perform addition (+), subtraction (-) and coefficient multiplication (an where a is a number)):

div:nth-child(4n)

Also, for pseudo-classes, use :, not ..


By the way, there's not much of a difference between 4n and 4n + 4 with regards to nth-child(). If you use the n variable, it starts counting at 0. Subsequently, this is what each selector would select:

:nth-child(4n)

4(0) = 0
4(1) = 4
4(2) = 8
4(3) = 12
4(4) = 16
...

:nth-child(4n + 4)

4(0) + 4 = 0  + 4 = 4
4(1) + 4 = 4  + 4 = 8
4(2) + 4 = 8  + 4 = 12
4(3) + 4 = 12 + 4 = 16
4(4) + 4 = 16 + 4 = 20
...

Both select the 4th, 8th, 12th and 16th elements that you're looking for. Therefore, there's no difference in your question's context.