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

Jonathan Gurr
PLUS
Jonathan Gurr
Courses Plus Student 1,859 Points

How to select the 3rd through 5th element out of 10

So I was watching this video on the nth-child, and I was wondering if there is a way to select for example 3 through 5 but that's it no more.

1 Answer

James Barnett
James Barnett
39,199 Points

nth-child ranges can be tricky so, let's break it down into 3 simple steps and use a graphical example.


We start out with:


Step 1: Count forward from 3

  • That's n+3
  • the n tells us to count every element going forward
  • the +3 tells us to start counting at 3

So the CSS is:

nth-child(n+3){ background: indianred; }

Which will give us:


Step 2: Count backward from 5

  • That's -n+5
  • the -n tells us to count every element going backward, the minus is for backward
  • the +5 tell us to start counting at 5

So the CSS is:

nth-child(n-5)

Which will give us:


Step 3: Combine the 2 steps and CSS does it's magic

Combine the 2 nth-childs into a single selector using the : combinator

nth-child(n+3):nth-child(-n+5)

We end up with:


So the take away from all of this is that it doesn't matter the number of elements you have, you just need to combine the 2 nth-childs together


I made you a little nth-child playground go nuts.

http://codepen.io/jamesbarnett/pen/tlBfp