views:

131

answers:

3

Hi,

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?

+8  A: 

Well, it's called nth-child(), so use the n variable and work with it (you can do basic arithmetic on it + - * / although only multiplying is necessary here):

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 to select. Therefore, no difference in your question's context.

BoltClock
+1 to the fastest gun!
LeguRi
+1  A: 
div.nth-child(4n+4) 

See: http://css-tricks.com/how-nth-child-works/

Tomalak
+1  A: 

Try this

div.nth-child(4n+4)
Marko