CSS :nth-last-child Selector

❮ Previous Selectors Next ❯

Example

/* Sets the color to red if the p element is its parents second to last child */
p:nth-last-child(2) {
  background: red;
}

Meaning

The :nth-last-child() selector selects the element that is the nth from last child of its parent.

The :nth-last-child() pseudo-class is specified with a single argument, which represents the pattern for matching elements, counting from the end.

Version: CSS3




Standard Syntax

:nth-last-child(n|odd|even|An+B) {
  css declarations;
}



Browser Support

The numbers in the table specify the first browser version that fully supports the property.




Status







Parameter values

The following table describes the values of this selector parameter.

Value Description
n Specifies the number to selects the element that is the nth from last child of its parent.
odd Defines elements whose numeric position in a series of siblings is odd: 1, 3, 5, etc.
even Defines elements whose numeric position in a series of siblings is even: 2, 4, 6, etc.
An+B Defines elements in a list whose indices match those found in a custom pattern of numbers, defined by An+B, where:
  • A is an integer step size
  • B is an integer offset
  • n is all nonnegative integers, starting from 0.



Example selectors

tr:nth-last-child(odd) or tr:nth-last-child(2n+1)

Represents the odd rows of an HTML table: 1, 3, 5, etc., counting from the end.

tr:nth-last-child(even) or tr:nth-last-child(2n)

Represents the even rows of an HTML table: 2, 4, 6, etc., counting from the end.

:nth-last-child(7)

Represents the seventh element, counting from the end.

:nth-last-child(5n)

Represents elements 5, 10, 15, etc., counting from the end.

:nth-last-child(3n+4)

Represents elements 4, 7, 10, 13, etc., counting from the end.

:nth-last-child(-n+3)

Represents the last three elements among a group of siblings.

p:nth-last-child(n) or p:nth-last-child(n+1)

Represents every <p> element among a group of siblings. This is the same as a simple p selector. (Since n starts at zero, while the last element begins at one, n and n+1 will both select the same elements.)

p:nth-last-child(1) or p:nth-last-child(0n+1)

Represents every <p> that is the first element among a group of siblings, counting from the end. This is the same as the :last-child selector.

❮ Previous Selectors Next ❯