The :nth-last-child()
CSS pseudo-class matches one or more elements based on their position among a group of siblings, counting from the end.
/* Selects every fourth element among any group of siblings, counting backwards from the last one */ :nth-last-child(4n) { color: lime; }
Note: This pseudo-class is essentially the same as :nth-child
, except it counts items backwards from the end, not forwards from the beginning.
The nth-last-child
pseudo-class is specified with a single argument, which represents the pattern for matching elements, counting from the end.
odd
even
<An+B>
An+B
, for every positive integer or zero value of n
. The index of the first element, counting from the end, is 1
. The values A
and B
must both be <integer>
s.:nth-last-child( <nth> [ of <selector># ]? )where
<nth> = <an-plus-b> | even | odd
tr:nth-last-child(odd)
or tr:nth-last-child(2n+1)
tr:nth-last-child(even)
or tr:nth-last-child(2n)
:nth-last-child(7)
:nth-last-child(5n)
:nth-last-child(3n+4)
:nth-last-child(-n+3)
p:nth-last-child(n)
<p>
element among a group of siblings. This is the same as a simple p
selector.p:nth-last-child(1)
or p:nth-last-child(0n+1)
<p>
that is the first element among a group of siblings, counting from the end. This is the same as the :last-child
selector.<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>
table { border: 1px solid blue; } /* Selects the last three elements */ tr:nth-last-child(-n+3) { background-color: pink; }
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. |
Feature | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | 4 | Yes | 3.5 | 9 | 9 | 3.2 |
Matches elements with no parent | 57 | ? | 52 | ? | 44 | ? |
Feature | Android webview | Chrome for Android | Edge mobile | Firefox for Android | Opera Android | iOS Safari | Samsung Internet |
---|---|---|---|---|---|---|---|
Basic support | Yes | Yes | Yes | 4 | 10 | 3.2 | ? |
Matches elements with no parent | 57 | 57 | ? | 52 | 44 | ? | ? |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child