MDN will be in maintenance mode on Friday September 22nd, starting at 10 AM Pacific / 5 PM UTC, for about 1 hour.

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.


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

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


Example selectors

Represents the last four rows of an HTML table.
Represents the even span elements, starting at the last element and going backwards.

Example usage


      <td>First line</td>
       <td>Second line</td>
       <td>Third line</td>
       <td>Fourth line</td>
       <td>Fifth line</td>


table {
  border: 1px solid blue;

/* Select the last three elements */
tr:nth-last-child(-n+3) {
  background-color: lime;



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,