Nth-child selectors

:nth-child(n)

The :nth-child pseudo-class targets a child element in relation to its position within the parent element. A list of blog comments, for example, might look nice with alternating background colors.

Alternating comment example:

How do you use nth-of-type?

  1. January 14, 2015

    Ian

    Wow! these CSS selectors are so amazing.

    Wow! these CSS selectors are so amazing.

  2. January 15, 2015

    James

    The :nth-child pseudo-class targets a child element in relation to its position within the parent element.

  3. January 15, 2015

    Jess

    I find it really useful to use the :nth-child() pseudo-class to target even-numbered and odd-numbered list items.

  4. January 16, 2015

    Lachlan

    The :nth-last-child(n) pseudo-class works just like :nth-child(n), except the order is determined in relation to the last child element, rather than the first.

  5. January 17, 2015

    Sasha

    I use first-of-type all the time. The :first-of-type pseudo-class targets the first of a specific type of element within a parent.

  6. January 18, 2015

    Dane

    The :last-of-type pseudo-class targets just what the name says: the last element type within a parent. Sometimes this is just the ticket to always grab the last item of a list.

  7. January 20, 2015

    Rye

    The :only-of-type pseudo-class targets a child element that is the only one of its type within the parent element. This is the n.o.t. selector I get the most mileage from.

  8. January 20, 2015

    Aya

    The :nth-of-type(n) pseudo-class works similarly to the other numeric-based pseudo-classes I’ve covered. This pseudo-class targets a specific element type according to its position relative to the parent element.

  9. January 21, 2015

    Prof. S

    I like :first-child. The :first-child pseudo-class targets the first child element, regardless of type, in a parent element.

As you can see, nth-of-type selectors can really help you selecting various elements within your web pages.