CSS :nth-last-of-type()
Pseudo-Class
The :nth-last-of-type(n)
pseudo-class selects an element based on its position among elements of the same type, counting from the end.
1. Syntax
✅ Works like :nth-of-type()
, but it starts counting from the last matching element instead of the first.
2. Example – Targeting List Items from the End
✅ The second-to-last <li>
(Item 4) will be red and bold.
3. Using Formulas (an + b
)
You can use the same formulas as in :nth-of-type()
:
Formula | Effect |
---|---|
:nth-last-of-type(1) | Selects the last matching element |
:nth-last-of-type(2) | Selects the second-to-last matching element |
:nth-last-of-type(odd) | Selects all odd-numbered elements from the end |
:nth-last-of-type(even) | Selects all even-numbered elements from the end |
:nth-last-of-type(3n + 1) | Selects every third element, starting from the last one |
Example – Styling Odd Elements from the End
✅ Every odd-numbered <p>
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-of-type()
vs. :nth-last-child()
Pseudo-Class | Applies To | Condition |
---|---|---|
:nth-last-of-type(n) | Any element | Selects the n -th last of its type inside its parent. |
:nth-last-child(n) | Any element | Selects the n -th last child (of any 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-of-type(n)
for styling elements based on position from the end.
✔ Works well for dynamic content, like comments, chat messages, or lists.
✔ Use :nth-of-type(n)
instead of counting from the start.