CSS :nth-last-of-type() Pseudo Class

CSS :nth-last-of-type() Pseudo Class

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

selector:nth-last-of-type(n) { /* Styles for the nth last matching element */ }

✅ 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

<ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> <li>Item 5</li> </ul>
li:nth-last-of-type(2) { color: red; font-weight: bold; }

✅ 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():

FormulaEffect
: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

p:nth-last-of-type(odd) { background-color: lightblue; }

✅ Every odd-numbered <p> from the end gets a light blue background.

4. Example – Styling Table Rows from the End

<table> <tr><td>Row 1</td></tr> <tr><td>Row 2</td></tr> <tr><td>Row 3</td></tr> <tr><td>Row 4</td></tr> <tr><td>Row 5</td></tr> </table>
tr:nth-last-of-type(1) { background-color: yellow; }

✅ The last <tr> (Row 5) will have a yellow background.

5. :nth-last-of-type() vs. :nth-last-child()

Pseudo-ClassApplies ToCondition
:nth-last-of-type(n)Any elementSelects the n-th last of its type inside its parent.
:nth-last-child(n)Any elementSelects the n-th last child (of any type) inside its parent.

Example

<div> <p>Paragraph 1</p> <span>Span 1</span> <p>Paragraph 2</p> <span>Span 2</span> <p>Paragraph 3</p> </div>
p:nth-last-of-type(2) { color: red; } p:nth-last-child(2) { color: blue; }

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.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close