Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS CSS Foundations Advanced Selectors Pseudo-Classes: :nth-of-type and :only-of-type

Zach Saul
Zach Saul
11,156 Points

Why use "nth-of-type" instead of "nth-child"?

I' not clear on why one might need to use "nth-of-type" as opposed to "nth-child" in their code. isn't the selector before nth-child

for example:

li:nth-child(3) {}

enough to tell the browser what sort of elements we're referring to?

I'm at 2:30 in the video if that helps.

just unclear on why this is necessary.

1 Answer

Jacob Miller
Jacob Miller
12,466 Points

nth-child doesn't take into account the type of elements. So for example, if you had this code:

<div>
    <h1></h1>
    <p></p>
    <p></p>
</div>

writing p:nth-child(2) would select the first p element, because it is the second child. But writing p:nth-of-type(2) would select the second p element because it is the second paragraph child. So they're very similar, but in certain cases it would definitely make more sense to use nth-of-type over nth-child. It might be helpful to play around with the selectors in this w3 example: http://www.w3schools.com/cssref/tryit.asp?filename=trycss3_nth-child

Jacob Miller
Jacob Miller
12,466 Points

I might also add that writing p:nth-child(1) for the above code would not select anything, because there are no paragraph elements that are the first child.