CSS :nth-last-child Pseudo Class

CSS :nth-last-child Pseudo Class

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

selector:nth-last-child(n) { /* Styles for the nth last child */ }

✅ Similar to :nth-child(n), but counts from the last child instead of the first.

2. Example – Styling the 2nd Last Child

<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-child(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 numeric patterns just like :nth-child():

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

li:nth-last-child(odd) { background-color: lightblue; }

✅ Every odd-numbered <li> 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-child(1) { background-color: yellow; }

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

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

Pseudo-ClassApplies ToCondition
:nth-last-child(n)Any elementSelects the n-th last child (of any type) inside its parent.
:nth-last-of-type(n)Any elementSelects the n-th last of its 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-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.

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