A Practical Look at :first-child, :last-child, :nth-child, and :nth-last-child

Published:

The :first-child, :last-child, :nth-child, and :nth-last-child pseudo-class selectors are all used to target a specific child element under its parent. The main difference is simply the position of the child being selected.

Most mainstream browsers support these selectors, except for IE8 and earlier.

:first-child

:first-child selects the first element in a list.

li:first-child{background:#f00}

The code above means setting the background color of the first li inside the list.

:last-child

:last-child selects the last element in a list.

li:last-child{background:#f00}

:nth-child(3)

This selects the third element in a list.

li:nth-child(3){background:#f00}

The number 3 can be changed to any other number, such as 4 or 5. If you want to select the nth item, just write that number.

:nth-child(2n)

This selects the even-numbered items in a list, meaning the 2nd, 4th, 6th, and so on.

:nth-child(2n-1)

This selects the odd-numbered items in a list, meaning the 1st, 3rd, 5th, 7th, and so on.

:nth-child(n\+3)

This selects items starting from the third one through the end of the list.

:nth-child(-n\+3)

This selects items from the beginning up to the third one, that is, the first three items.

:nth-last-child(3)

This selects the third item counted from the end of the list.