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

What's the difference between the :nth-child and :nth-of-type pseudo classes?

Is there's difference at all?

3 Answers

nth-child will only look through child nodes. That is, any node that is inside of your selector. nth-of-type goes through the whole DOM and looks for anything that matches your selector. For instance, lets say you have this HTML:

<p>First</p>
<div>
<p>Second</p>
<p>Third</p>
</div>

Say you want to target the paragraph that contains "Second" inside of it. We can match it by using looking for children of the div or by looking through all paragraphs. Here's the CSS showing both:

div:nth-child(1) {
color: blue;
}
p:nth-of-type(2) {
color: blue;
}

They both would do the same thing, make the second paragraph in the DOM blue. The reason the number in parenthesis is different is because the paragraph we want is the second element of type "p" in the DOM as a whole, but it is the first child of the element "div".

Does that make sense?

Thanks Nick. I was getting frustrated for a few seconds. That makes perfect sense.

One matches all types, the other a specific type

Ok I'm going to revisit. But now I know what to look for exactly. Thanks.

Nick, you are a life saver! That makes perfect sense.

No sweat!