A Brief Introduction

It’s easy to miss out on a lot of CSS functionality if you’re unaware of the advanced selectors. Things like :first-child, :last-child, and :nth-child can really come in handy in certain situations. Today, we’ll take a look at all 3 of these advanced selectors, and see how they can help us target some hard to reach elements on our page. Ready? Let’s do it.

Step 1: The HTML

We’ll be using a fairly large unordered list to demonstrate some of the capabilities of the advanced selectors. This will give us plenty of elements to traverse, and provides an easy way to see how the selectors work. Here’s the initial HTML page with the list already set up:

Step 2: The CSS

On to the styles! We’ll start with the :first-child and :last-child pseudo-classes. These, as you may have guessed, take the element that we are referencing as the parent element. In our case, the parent element will be the list with the ID of theList. The element may have several children, in our example, theList has 15 children to be exact. So if we call the :first-child or :last-child, you should expect to see the styles added to the first and last item. Let’s add some styles to the first and last child now:

Now, if you load up the page in the browser, you’ll see exactly what you should expect. The first list item is colored a light-yellow, and the last a light-green. The first and last child pseudo selectors have easily allowed us to call out these items and style them.
The next pseudo-class we’ll take a look at is the :nth-child() selector. This selector is great for when you need to style, say, only the odd elements or only the even elements. The number that we pass into the selector will determine which one of the children is to be styled. For instance, if we pass in a “2″, it will style the second child of the parent element. If we pass in “2n”, it will style every second child of the parent element. Let’s style every 4th child in our list:

You could pass in any number you’d like to the nth-child() pseudo-class and CSS will find every one of those numbered children and style them to your heart’s content. Again, this comes in handy when you’d like to have alternating styles for rows in, say, a table, that will make it easier for your visitors to visualize the information.

A Few Last Words

Getting the hang of using the pseudo-classes in CSS will give you an edge above the average web designer. Not only that, but it will help you to keep from using unnecessary classes and ID’s when creating your pages. Join us in our next tutorial, part 2, when we’ll dig deeper into the more advanced selectors in the wonderful world of CSS. See you then!

Download Source Files