CSS :nth-last-child
Pseudo-Class
The :nth-last-child(n)
pseudo-class selects an element based on its position among all children, counting from the end.
1. Syntax
✅ Similar to :nth-child(n)
, but counts from the last child instead of the first.
2. Example – Styling the 2nd Last Child
✅ The second-to-last <li>
(Item 4) will be red and bold.
3. Using Formulas (an + b
)
You can use numeric patterns just like :nth-child()
:
Formula | Effect |
---|---|
:nth-last-child(1) | Selects the last child |
:nth-last-child(2) | Selects the second-to-last child |
:nth-last-child(odd) | Selects all odd-numbered children (from the end) |
:nth-last-child(even) | Selects all even-numbered children (from the end) |
:nth-last-child(3n + 1) | Selects every third child from the end, starting with the last |
Example – Styling Odd Elements from the End
✅ Every odd-numbered <li>
from the end gets a light blue background.
4. Example – Styling Table Rows from the End
✅ The last <tr>
(Row 5) will have a yellow background.
5. :nth-last-child()
vs. :nth-last-of-type()
Pseudo-Class | Applies To | Condition |
---|---|---|
:nth-last-child(n) | Any element | Selects the n -th last child (of any type) inside its parent. |
:nth-last-of-type(n) | Any element | Selects the n -th last of its type inside its parent. |
Example
✅ p:nth-last-of-type(2)
→ Selects Paragraph 2 (second-to-last <p>
).
❌ p:nth-last-child(2)
→ Does nothing because the second-to-last child is <span>
.
6. Browser Support
✅ Fully supported in Chrome, Edge, Firefox, Safari, and Opera.
7. Best Practices
✔ Use :nth-last-child(n)
for styling elements based on position from the end.
✔ Great for dynamic content, like comments, chat messages, or lists.
✔ Use :nth-child(n)
instead if counting from the start.