:nth-last-child

The :nth-last-child(an+b) CSS pseudo-class matches an element that has an+b-1 siblings after it, where n is positive or zero. It is essentially the same as :nth-child, except it counts items backwards from the end, not forwards from the beginning.

/* Selects every fourth child element inside the body */
/* regardless of element type */
/* counting backwards from the last one */
body: nth-last-child(4n) {
  background-color: lime;
}

See :nth-child for a more thorough description of the syntax of its argument.

Syntax

:nth-last-child( <nth> [ of <selector># ]? )

where
<nth> = <an-plus-b> | even | odd

Examples

Example selectors

tr:nth-last-child(-n+4)
Represents the last four rows of an HTML table.
span:nth-last-child(even)
Represents the even span elements, starting at the last element and going backwards.

Example usage

HTML

<table>
  <tbody>
    <tr>
      <td>First line</td>
    </tr>
    <tr>
       <td>Second line</td>
    </tr>
    <tr>
       <td>Third line</td>
    </tr>
    <tr>
       <td>Fourth line</td>
    </tr>
    <tr>
       <td>Fifth line</td>
    </tr>
  </tbody>
</table>

CSS

table {
  border: 1px solid blue;
}
/* Select the last three elements */
tr:nth-last-child(-n+3) {
  background-color: lime;
}

Result

Specifications

Specification Status Comment
Selectors Level 4
The definition of ':nth-last-child' in that specification.
Working Draft Matching elements are not required to have a parent.
Selectors Level 3
The definition of ':nth-last-child' in that specification.
Recommendation Initial definition.

Browser compatibility

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support 4 (Yes) 3.5 (1.9.1) 9.0 9.5 3.2
No parent required 57 ? 51 (51)[1] ? 44 ?
Feature Android Webview Chrome for Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) 1.0 (1.9.1) 9.0 10 3.2
No parent required 57 57 ? 51.0 (51)[1] ? 44 ?

 

[1] See bug 1300374.

See also

Document Tags and Contributors

 Last updated by: mfluehr,