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

Matthew Meo
Matthew Meo
2,341 Points

CSS nth-child Values

So I now understand the concept of the nth-child in CSS (thanks Guil!). I'm just wondering what common real life situations would call for using these. Can anyone think of any examples where this would be needed in a web project?

Thanks!

4 Answers

Nicholas Olsen
seal-mask
.a{fill-rule:evenodd;}techdegree
Nicholas Olsen
Front End Web Development Techdegree Student 19,342 Points

You can use nth-child(even) to create alternating background colors in table rows like you see here.

I don't know how well you know SASS but this guy created a self correcting grid list with nth-child that I think is pretty cool. That guy in particular is (or was?) really into creating entire designs without using classes or IDs so you can see a lot of pseudo selectors and CSS3 selectors in his work.

Another idea might be to use it to select elements at specific intervals at different breakpoints to make a design responsive. For example, you can have a row of 6 elements at a large screen size, and then at a smaller screen size make them rows of 4 elements using nth-child(4n). Then at a smaller screen size create rows of 2 elements using nth-child(2n). I'm just brainstorming at this point.

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Matthew:

I would take a look here for some examples.

Ken

Chris Shaw
Chris Shaw
26,650 Points

Useful :nth-child Recipes by Chris Coyier is a great resource, it's a simple page overviewing different values nth-child accepts.

Matthew Meo
Matthew Meo
2,341 Points

This is all great stuff! It really makes a lot of sense that simple color changes on tables can make it easier on the eye to read. Thanks for these links everyone. This is my first forum post, so I'll have to do more. Response time was insane. Thanks!