Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Erik Krieg
Erik Krieg
43,038 Points

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.

Erik Krieg
Erik Krieg
43,038 Points

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!