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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
As the name implies,
:nth-child()allows you to construct an arithmetic expression using thenvariable in addition to constant numbers. You can perform addition (+), subtraction (-) and coefficient multiplication (anwhereais 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 ash1orp, you will need to use:nth-of-type()instead of:nth-child()to ensure you only countdivelements: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 thenvariable, 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.