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

create a new rule that targets the last 3 list items only. Set the font size to 30px.

li:nth-child(n-4){ font-size:30px; }

why is this wrong?

Do you know exactly hoy many <li> are there, do you plan on adding more?

2 Answers

Brian Molkovich
Brian Molkovich
11,333 Points

ul li:nth-child(7n){ font-size:30px; } ul li:nth-child(6n){ font-size:30px; } ul li:nth-child(5n){ font-size:30px; }

This does pass the code challenge for me. Are you wondering why it passes even though it makes all the list items 30px?

My guess is that the code checker is only checking that the last 3 items are 30px and not checking if you've accidentally made the other items 30px.

Your selector li:nth-child(n-4) is actually selecting every single item.

To see why, you can substitute values for n, starting at zero, and see what the expression evaluates to.

n | n-4
0 | -4
1 | -3
2 | -2
3 | -1
4 | 0
5 | 1
6 | 2
7 | 3

Positive values in the right column indicate which children will be selected. The first child is #1. So we can see that eventually when n becomes 5, the first child will be selected and then the 2nd, and so on. All the children will be selected with this expression.

Using nth-child, you need an expression that will start at the 5th child and select everything after as well.

li:nth-child(n+5) This will start at the 5th child and continue selecting everything after. Try making a table as I did above to see this. However, this only works in this very specific example of a 7 item list. It doesn't work for a list of any length when you want the last 3 items.

It would be better to use li:nth-last-child(-n+3) for this. This expression is saying start with the 3rd element from the end and then select every element after that.

You can see this better in a table:

n | -n+3
0 | 3
1 | 2
2 | 1
3 | 0
4 | -1
5 | -2
6 | -3
7 | -4

Looking at the positive values in the right column, we can see that it will select the 3rd, 2nd, and 1st child, from the end, and it won't select any more than that.