Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Nth-child selectors

From: CSS: Core Concepts

Video: Nth-child selectors

Of all the structural pseudo-class selectors, the most complex of them are the nth-child pseudo-class selectors. Nth-child selectors allow us to target elements based on patterns that describe which elements within a parent that you should target. Now we have four flavors of nth-child selector available to us. There is nth-child, nth of type, nth last child and last of type. Now the syntax of these selectors can seem a little odd the first time you see it. In fact, I've pulled up the Selectors Level 3 specification for you to take a quick look at this, and you can see here are a couple of examples of the nth-child syntax, and this is the symbol syntax.

Nth-child selectors

Of all the structural pseudo-class selectors, the most complex of them are the nth-child pseudo-class selectors. Nth-child selectors allow us to target elements based on patterns that describe which elements within a parent that you should target. Now we have four flavors of nth-child selector available to us. There is nth-child, nth of type, nth last child and last of type. Now the syntax of these selectors can seem a little odd the first time you see it. In fact, I've pulled up the Selectors Level 3 specification for you to take a quick look at this, and you can see here are a couple of examples of the nth-child syntax, and this is the symbol syntax.

So the first time you see this, it can be a little overwhelming. It looks like you're doing math. You've got this weird stuff going on here. But don't panic. It's actually pretty easy syntax. The only difference with nth-child and some of the others syntax that we are using is that you have the sort of argument that you can pass values into and that describes the pattern that is going to be targeted. It makes a lot more sense once you start working with it a little bit, so we are going to jump into our exercise files and start working with the nth-child selector. Okay, so here I've opened up the nth-child.htm, and you can find that in the 02_16 directory.

Now, very simple page structure. We just have an ordered list on the page and inside that ordered list there are twenty items, all list items, and we are going to use nth-child selectors to target some of those list items. Now we have some default styling. We just have sort of a beige background color for these and if I were to preview this in my browser, you can kind of see what we have going on here. We just have beige backgrounds for each of these list items. So what I am going to do is in the styles of my document, just below the existing li style, I am going to write a very simple nth-child selector.

I am going type in li:--so again it is a pseudo-class selector, li:--nth-child and then immediately after nth-child no spacing; I have to open up a parentheses. And what I am going to do here is I am just going to type in the number 2. So I am passing in the number 2. After that, I am going to open up my brackets and I am just going to type in background: tan. Okay, Aptana doesn't like tan, but I assure you, that color is supported by browsers.

So, again what we've got going on here is we are saying, hey, nth-child, go through the pattern and match it, and we are just passing the number 2, and that's going to tell it to target the second element within that pattern. So I am going to go ahead and preview that in my browser. So let me just refresh that, and you can see that indeed it goes ahead and targets the second item with that styling. So when you pass a single number in that, it's just going to count down through the items in the parent element, and it's going to target the one you're looking for. Now I want to point out something very important about this.

We are going to be using ordered lists for this example, and the ordered list is typically, in terms of children, it's going to just have list item children, but occasionally you're going to have repeating structures that have additional elements inside of it. That's very important for you to know that even though we are targeting list items, it's looking through every single child when it does this, not just list items. So for example, if I said p here, instead of a paragraph--this is bad syntax, so just bear with me for a second here; I am just illustrating the concept.

Now if I save this and preview that in my browser, it no longer gets that styling. It no longer gets that styling because the second item inside the ordered list is no longer a list item, so it has to match that. So that's one of the really important things. It's not just counting the list items; it's counting every element. Now that that's out of the way, let's take a look at how we could maybe modify this a little bit. I am going to change the 2 from 2 to 2n. Now this n is a grouping element.

What this does is it says, instead of just targeting the second element, target every second element. So it creates a sort of repeating pattern where it's grouping every second element. So I am going to save that and test that in my browser, and hey, look at that: Now every second element is targeting. And how easy is that now to do alternating colors and tables and lists like this, whereas before you had to either use JavaScript or you can do a lot of manual class application with nth-child that's just really, really simple.

Now in addition to having this sort of grouping, we do have keywords that we could use. So I could say, for example, I could say odd. Save that, test it, and now notice that every odd list item is getting that. I could also go ahead and type in even. It's another keyword I can use. And when I type in even, I would get the result that we had before. So we had the odd and even keyword, and we have groupings as well. Now in addition to being able to group things together, we also have what we call an offset. So if I type in 2n-- remember, that's what we just had-- so this is going to get every second.

Well, I can also do an offset. I can do +1. Now let me talk about what this offset is. This offset changes where you begin within the count. We always start counting at 1, but when you do an offset, it basically says okay, grab every second one, beginning with this one. So if I save this and test it, notice that that's just another way of doing every odd one, because it's saying start to count at 1, which is the first item, and then do every second one. So now we are getting all their odds. So that's what the offset allows us to do.

It requires a little bit of thinking, but let's say we wanted to start with the fifth element and then grab every fifth element after that. So to grab every fifth element, we would make sure our grouping says 5n and then to start at the fifth element, we want to make sure that we started at number 5, so 5n+5. So if I save this and test it, you can see it does exactly that for us. It starts at number 5 and then it gives us every fifth element after that. So really, once you know what these items within the selector are doing, it becomes pretty easy to target exactly what you're looking for.

Now in addition to the sort of simple formatting that we can do here, we can also use negative values, and negative values really dramatically change how this works. So let's take a look at that. I am going to change this grouping. Instead of 5, I am going to change it to -2, and then I am going to start with a count of 8. So what a negative number on the grouping does for us is instead of counting up the way it's done where you go every second, it's going to start wherever its count is and then it's going to go backwards. So instead of going down the list, it's going to go up the list.

By starting at number 8 it's going to go to the eighth item in the list, and then it's going to select every second one going backwards up the list. Let's check that out. So if I save this, preview this again, you can see what I am talking about. It starts at number eight, and then it targets every second one after that until it sort of runs out of it. So instead of counting down the list, the negative values cause it to count up. Now when you use a negative value for the offset, really strange things happen. Let me show you what I mean. So if I change my grouping to 5n, we know that's going to be every fifth element.

So if I do an offset. Instead of +1, I do -1, let's see what that does. So I am going to save this, preview this, and I can see that instead of every fifth element, now it's starting at number 4, and then I am getting every fifth element. So what's it doing there? Well, remember what that offset count does. If I had started, say, at number 5. By doing -1, essentially what it's doing for me is it's just shifting everything up by 1. So whereas before, it would grab 5 and 10, now it's shifting everything sort of up, if you will, in the count and I am starting at 4, but I am still spacing everything by 5.

So if we change that to 2, it does exactly what you'd expect: it just shifts up. So what if it started at 5, but it shifts up. These are fairly simple child selectors. Let's take a look at how we can make them a little bit more complex. I am going to do a comment, so that's /*, and then I am just going to do simple nth-child. And then at the end of this selector I'm going to do a */ and that ends the comment. Now below that, I am going to type in /* complex nth child and then a */ to end that comment.

So again /* starts a comment, */ ends it. So now let's take a look at a very complex nth-child selector. One of the things that you can do with nth-child selectors is you can kind of daisy-chain them together, and in sort of stringing these together you can target these very complex contiguous patterns. Let me show you what I mean. Let's type in li:nth-child(1n+6). All right, let's start about what this would do.

This is going to select every single element, every grouping of 1, and it's going have an offset of 6. So that would start with the sixth element and then it would just select every one there after that. Well, I can also group this, or daisy- chain it if you will, or combine it, with another nth-child selector. So immediately after that, I am going to type in :nth-last-child. Now we haven't used this one yet. So anything pass nth-child, like last- child, that's going to say go to the bottom of the list and start counting from the bottom of the list up.

Nth-child starts at the top of the list and counts down. So here we are going to say 1n+6. So we are doing the same thing. Now I am going to step outside of this and just go ahead and apply some basic formatting to that. I am going to do the same thing, background: tan. Now, let's talk about what this is going to do before we check it. We know that this is going to start at the sixth element and then just select every one after that. We know that this one is going to start from the sixth element at the end of our list, because again, this is an offset for last-child.

So the last-child would be the very last one, so if we do an offset by 6, that's counting up sixth element from the end, and it's going to select every element and up. So essentially what's going to happen is these guys are going to meet the middle. This is going to select all except for the first five elements and all except for the last five elements. Let's check it out. So I am going to save this and go back to my browser and preview that. And you can see it's doing exactly what we said it would do. It's going up to item number 6 and selecting every one from that point forward. The nth-last-child is going to item 15, which is the sixth offset, and going up.

So those two are meeting, and they're just sort of excluding the first five and excluding the last five. Now what if you wanted to go the opposite way with that and select only the first five and only the last five? Well, you can only daisy-chain, or sort of combine, these selectors like this when you have a contiguous selection. If your selection is noncontiguous, the only way that you can really do that is by grouping them. So let's see how we would do that. So I am going to go back to this selector, and I am going to change this to say -1+5.

Now remember what that would do. That would go to the fifth item and then because the grouping is negative -1, it would count up. So it would go the fifth item and it would select every item up to the first one. Now instead of being able to combine these together, I am going to have to do a grouping. So I am going to have to do, li: nth-last-child and I am going to do the same thing here, -1n+5. Again, what is this going to do? Because it's using last child, it's going to start at the very bottom. It's going to go up by five. So it's going to select fifth from the bottom and then because it's using a negative, instead of counting up the list towards the earlier ones, it's going to go down the list towards the last one.

So we are going to go ahead and save that, preview that in our browser, and we get the styling that we were expecting: first five and last five. Now look I know that that is a lot to take in if you've never worked with nth-child selectors and I don't want you to feel really upset if you don't get how the syntax works right off the bat. I really recommend using the exercise file that we've got here just as means of practicing, writing nth-child selectors. Sort of come up with these patterns in your mind and say using these selectors, how do I do that? You experiment with different values, experiment with different grouping selectors, experiment with negative values, and over time all this is going to become a lot clearer to you.

The more you work with these selectors, the more comfortable you're going to be writing them and writing them in the most efficient manner that you can for that particular situation. Now these selectors can be a little bit complex. As I mentioned before, there are actually multiple types of nth-child selectors. There are those four that we talked about. So be patient as you learn them, and don't rely on them until you feel like you have a really firm grasp of exactly which elements the selector will target. Again, for more information, be sure to go to the Selectors Level 3 Specification and look for the nth- child pseudo-class selectors.

They have a lot of examples here of syntax and a lot of extra information about it. So you can learn a lot just by going here as well and using the file that we just used to practice using some of these different formulas. Have fun using them. They're really powerful, really cool selectors that once you get the hang of, you will be using a lot.

Show transcript

This video is part of

Image for CSS: Core Concepts
CSS: Core Concepts

81 video lessons · 40277 viewers

James Williamson
Author

 
Expand all | Collapse all
  1. 4m 57s
    1. Welcome
      55s
    2. Using the exercise files
      4m 2s
  2. 1h 7m
    1. Exploring default styling
      4m 56s
    2. CSS authoring tools
      2m 29s
    3. CSS syntax
      4m 45s
    4. Writing a selector
      4m 10s
    5. Setting properties
      8m 40s
    6. Common units of measurement
      7m 47s
    7. Inline styles
      5m 1s
    8. Embedded styles
      5m 19s
    9. Using external style sheets
      10m 34s
    10. Checking for browser support
      8m 48s
    11. Dealing with browser inconsistencies
      5m 30s
  3. 2h 15m
    1. Structuring HTML correctly
      2m 51s
    2. Element selectors
      4m 52s
    3. Class selectors
      6m 4s
    4. ID selectors
      3m 27s
    5. Using classes and IDs
      10m 7s
    6. Element-specific selectors
      4m 35s
    7. The universal selector
      5m 42s
    8. Grouping selectors
      4m 49s
    9. Descendent selectors
      7m 32s
    10. Child selectors
      5m 7s
    11. Adjacent selectors
      5m 30s
    12. Attribute selectors
      12m 43s
    13. Pseudo-class selectors
      3m 54s
    14. Dynamic pseudo-class selectors
      8m 29s
    15. Structural pseudo-class selectors
      6m 45s
    16. Nth-child selectors
      13m 10s
    17. Pseudo-element selectors
      12m 40s
    18. Targeting page content: Lab
      8m 56s
    19. Targeting page content: Solution
      7m 59s
  4. 42m 39s
    1. What happens when styles conflict?
      4m 0s
    2. Understanding the cascade
      5m 47s
    3. Using inheritance
      6m 11s
    4. Selector specificity
      6m 55s
    5. The !important declaration
      4m 5s
    6. Reducing conflicts through planning
      3m 33s
    7. Resolving conflicts: Lab
      6m 45s
    8. Resolving conflicts: Solution
      5m 23s
  5. 1h 47m
    1. Setting a font family
      7m 10s
    2. Using @font-face
      9m 18s
    3. Setting font size
      7m 35s
    4. Font style and font weight
      6m 52s
    5. Transforming text
      3m 58s
    6. Using text variants
      2m 49s
    7. Text decoration options
      4m 26s
    8. Setting text color
      3m 2s
    9. Writing font shorthand notation
      8m 49s
    10. Controlling text alignment
      6m 33s
    11. Letter and word spacing
      9m 11s
    12. Indenting text
      4m 30s
    13. Adjusting paragraph line height
      10m 30s
    14. Controlling the space between elements
      6m 41s
    15. Basic text formatting: Lab
      8m 45s
    16. Basic text formatting: Solution
      7m 14s
  6. 2h 1m
    1. Understanding the box model
      16m 53s
    2. Controlling element spacing
      14m 29s
    3. Controlling interior spacing
      10m 49s
    4. Margin and padding shorthand notation
      6m 27s
    5. Adding borders
      8m 57s
    6. Defining element size
      10m 7s
    7. Creating rounded corners
      6m 58s
    8. Background properties
      2m 51s
    9. Using background images
      5m 10s
    10. Controlling image positioning
      10m 25s
    11. Using multiple backgrounds
      7m 5s
    12. Background shorthand notation
      5m 25s
    13. Styling container elements: Lab
      7m 55s
    14. Styling container elements: Solution
      8m 17s
  7. 47m 51s
    1. Color keyword definitions
      5m 4s
    2. Understanding hexadecimal notation
      6m 5s
    3. Using RGB values
      4m 58s
    4. Using HSL values
      5m 17s
    5. Working with opacity
      2m 23s
    6. Using RGBa and HSLa
      3m 8s
    7. Styling drop shadows
      5m 38s
    8. CSS gradients
      6m 32s
    9. Working with color: Lab
      4m 26s
    10. Working with color: Solution
      4m 20s
  8. 1m 58s
    1. Additional resources
      1m 58s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now "Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed CSS: Core Concepts.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.