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?
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?
You need the correct argument for the
nth-child
pseudo class.The argument should be in the form of
an + b
to match every ath child starting from b.Both
a
andb
are optional integers and both can be zero or negative.a
is zero then there is no "every ath child" clause.a
is negative then matching is done backwards starting fromb
.b
is zero or negative then it is possible to write equivalent expression using positiveb
e.g.4n+0
is same as4n+4
. Likewise4n-1
is same as4n+3
.Examples:
Select every 4th child (4, 8, 12, ...)
Select every 4th child starting from 1 (1, 5, 9, ...)
Select every 3rd and 4th child from groups of 4 (3 and 4, 7 and 8, 11 and 12, ...)
Select first 4 items (4, 3, 2, 1)
See: http://css-tricks.com/how-nth-child-works/
Try this
As the name implies,
:nth-child()
allows you to construct an arithmetic expression using then
variable in addition to constant numbers. You can perform addition (+
), subtraction (-
) and coefficient multiplication (an
wherea
is an integer, including positive numbers, negative numbers and zero).Here's how you would rewrite the above selector list:
For an explanation on how these arithmetic expressions work, see my answer to this question, as well as the spec.
Note that this answer assumes that all of the child elements within the same parent element are of the same element type,
div
. If you have any other elements of different types such ash1
orp
, you will need to use:nth-of-type()
instead of:nth-child()
to ensure you only countdiv
elements:For everything else (classes, attributes, or any combination of these), where you're looking for the nth child that matches an arbitrary selector, you will not be able to do this with a pure CSS selector. See my answer to this question.
By the way, there's not much of a difference between 4n and 4n + 4 with regards to
:nth-child()
. If you use then
variable, it starts counting at 0. This is what each selector would match::nth-child(4n)
:nth-child(4n+4)
As you can see, both selectors will match the same elements as above. In this case, there is no difference.