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-child

nth:child()

OK so, i'm so confused as to why if you have a < ul > parent element and 10 < li > child elements nested inside how does the browser know that you want to target the < li > within the < ul > if you do

li:nth-child (even) {}

because to me this looks like it would target any li's on the page and give them the nth-child attribute that we apply in the CSS.

i know this is wrong but to me i feel like it would make more since if the code was:

ul:nth-child (even) {}

because this way sounds like it is targeting all of the even children within the ul attribute. Can someone please explain how the first way works and how it knows which li on the page to target with the CSS?

3 Answers

You are right, li:nth-child(even) will indeed target li elements on the page no matter what their parent element so long as their place in their parent element is even.

If you wanted a more specific selector you could do ul li:nth-child(even) or .my-class li:nth-child(even)

Be sure to check this link if you want more info on this pseudo selector.

I also created this codepen to show you some simple examples. Feel free to mess around with it if you like :)

If you dont assign a class or id somewhere, the;

li:nth-child (even) {}

will target every <li> tag on the page and go through them in descending order, applying CSS to every other tag. If you're trying to target only a specific group of <li> tags, you should give the <ul> parent a class or id. For example if the <ul> tag was

<ul class="list1">

then you could use this CSS to target only the children of the parent .list1

.list1 li:nth-child(even)

Thanks Guys, Erik your codepen and information provided was extremely helpful to the question i was asking!