CSS :nth-last-of-type

The :nth-last-of-type() CSS pseudo-class matches elements based on their position among a group of siblings, counting from the last element. This allows you to target specific elements for styling or manipulation.

The syntax for using :nth-last-of-type() is :nth-last-of-type(an+b), where n is a counter that starts at 0 and increases by 1 for each sibling element, and a and b are integers that define the pattern of elements to select.

Let's look at some examples to understand how :nth-last-of-type() works:

Example 1:


    ul li:nth-last-of-type(3) {
      color: red;
    }
  

Consider the following HTML structure:


    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
      <li>Item 4</li>
      <li>Item 5</li>
    </ul>
  
Result:
  • Item 1
  • Item 2
  • Item 3
  • Item 4
  • Item 5

In this example, the :nth-last-of-type(3) pseudo-class selects the third <li> element from the last, which is "Item 3". It applies a color: red; style to this element.

Example 2:


    table tr:nth-last-of-type(odd) td {
      background-color: lightblue;
    }
  

Consider the following HTML structure:


    <table>
      <tr>
        <td>1</td>
        <td>2</td>
      </tr>
      <tr>
        <td>3</td>
        <td>4</td>
      </tr>
      <tr>
        <td>5</td>
        <td>6</td>
      </tr>
    </table>
  
Result:
1 2
3 4
5 6

In this example, the :nth-last-of-type(odd) pseudo-class selects every odd row (<tr> element) from the last in the table and sets the background color of the cells (<td>) inside those rows to light blue.

By using the :nth-last-of-type() pseudo-class, you can target specific elements based on their position from the end of a sibling group, allowing for more targeted styling and customization in your CSS.