What does "child" refer to in the `nth-child` pseudo class?
I always use the
nth-child pseudo class incorrectly on my first try because I infer it to mean "select the nth child of this element."
e.g., If I wanted to select the second child of a container, this makes more sense to me:
But that doesn't do what I want. This does:
So what is child referring to? .child doesn't have any children. Wouldn't a more apt name for this be nth instead of nth-child?
I'm asking this question because I think I'll stop making this mistake when I understand the reasoning behind the name.2 Replies
it's the nth child of the parent node
like an index
Because the pseudo class is attached to
.child selector , it indicates that it’s referring to itself (like div.container means one element that is a div with a class of container where div .container is a div with a .container within ); if there was a space between .child :nth-child(2) it would refer to the elements within. Eg .container :nth-child(2) note the space ; .child:nth-child(2) note the lack of space
Other helpful pseudo classes in the same vein:
- .child:nth-of-type(2) which may click better and is safer to use
- newer and have to check support :nth-child(2 of .child) MDN Web Docs
:nth-of-type() - CSS: Cascading Style Sheets | MDN
The :nth-of-type() CSS pseudo-class matches elements based on their position among siblings of the same type (tag name).