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 Selectors Going Further with Attribute Selectors and Pseudo-Classes :first-child and :last-child

Wouldn't it just be easier to...

Instead of writing li:first-child and things like that? wouldnt it be easier just to create a class?

3 Answers

Ryan Field
PLUS
Ryan Field
Courses Plus Student 21,242 Points

Hi, James. Sometimes it is indeed easier to make a class, but sometimes it makes more sense to use a pseudo selector. For instance, if you have a long table of things and you want the last row to have a different colour, you could create a class, but if you ever have to update the list by adding more thing on the end in the future, you'll have to remember to move the class to the appropriate list item. Using :last-child here is like a 'set-it-and-forget-it' kind of option. Similarly, you can use things like :nth-child(even) to alternate background colours of table rows for readability without having to worry about adding a class to every other child element.

It's okay to create many classes, but in the same vein, you don't want to litter your HTML with unnecessary classes as your code can quickly become unmaintainable. The goal is to have your code with as little repetitiveness as possible, and using pseudo selectors allows us to do this quite easily.

Allan Glasier
Allan Glasier
Courses Plus Student 7,736 Points

I was thinking the same thing as Jay.

Thank you Ryan for the great answer, definitely cleared things up for me!

Thank you for the elaborate answer Ryan!

Ivan Franzone
Ivan Franzone
7,328 Points

I agree with Ryan. When weΒ΄re working with a set of elements (like lists), itΒ΄s more convenient to use selectors and pseudo-classes.