:nth-last-child()

:nth-last-child() – pseudo-class | Selectors Level 3

The :nth-last-child(an+b) works similar to nth-child() pseudo-class. The difference is that :nth-last-child selects elements from bottom of the parent element. It also accepts the “even” and “odd” values as arguments.

Syntax

:nth-last-child(an+b) {
    style properties
}

a, b – integers

n – 0, 1, 2, 3…

Examples

The Html code:

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>

Example 1

ul li:nth-last-child(1) {
    background:#FFB7C5;
}
  • 1
  • 2
  • 3

The selected element: 3


 

Example 2

ul li:nth-last-child(-n+2) {
    background:#FFB7C5;
}
  • 1
  • 2
  • 3

Selected elements: 2, 3. Two last elements are selected.


 

Example 3

ul li:nth-last-child(2) {
    background:#FFB7C5;
}
  • 1
  • 2
  • 3
  • 4
  • 5

The second last element is selected in the parent element.


Example 4

ul li:nth-last-child(3n+1){
    background:#FFB7C5;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Selected elements: 9, 6, 3.
3 * 0 + 1 = 1 -> first from bottom, number 9
3 * 1 + 1 = 4 -> fourth from bottom, number 6
3 * 2 + 1 = 7 -> seventh from bottom, number 3


Example 5

The Html code:

<div>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    <ul>
        <li>4</li>
        <li>5</li>
        <li>6</li>
    </ul>
    <ul>
        <li>7</li>
        <li>8</li>
        <li>9</li>
    </ul>
</div>
div ul:nth-last-child(-n+2) li:nth-last-child(1){
    background:#FFB7C5;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Selected elements: 9, 6. Last li items from two last ul elements.

Related

Resources

Browser compatibility

nth-last-child()

Internet Explorer
9.0
Firefox
3.5
Chrome
4.0
Safari
3.2
Opera
9.5
Mobile
Safari Mobile
3.2
Android
2.1
Chrome Mobile
works
IE Phone
works
Opera Mini
works
Opera Mobile
works