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

:nth-child not working

my code is

<ul id="nav">
    <li>
        <ul>
             <li></li>
         </ul>
     </li>
    <li>
        <ul>
             <li></li>
         </ul>
     </li>
    <li>
        <ul>
             <li></li>
         </ul>
     </li>
</ul>

css:

#nav ul:nth-child(1){
    left:-20px;
}
#nav ul:nth-child(2){
    left:-40px;
}
#nav ul:nth-child(3){
    left:-60px;
}

it is not working only this css code is applied to all ul lists

#nav ul:nth-child(2){
    left:-40px;
}

any solution?

3 Answers

The :nth-child pseudo selector is based on a set of elements that all belong to the same parent, in your above example the UL exists within another parent therefore there is no second or third child to find in the node list, see the below link which is a quick demo I setup to show a working example.

http://codepen.io/ChrisUpjohn/pen/b9448ada6879beaaedd642d93c4ae42f

@Chris - I noticed your codepen isn't actually valid CSS, but is SCSS. For someone that doesn't use SCSS, it's kinda like someone asking how to do something in CSS and a person using JavaScript to help answer the question.

Makes sense, I was simply trying to point out the following:

li:nth-child(1) ul {
    left: -20px;
}

li:nth-child(2) ul {
    left: -40px;
}

li:nth-child(3) ul {
    left: -60px;
}

Let's take a look at one of your selectors

#nav ul:nth-child(3)

This says select the 3rd child of the ul. Since all of the uls only have 1 li inside them, this doesn't work.

Instead select the ul that's inside of the 3rd `li, remember selectors are read left right to left.

#nav li:nth-child(3) ul

Thank You for your effort and valuable suggestion and my code is working