Open In App
Related Articles

CSS :nth-last-child() Selector

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

The nth-last-child() selector in CSS is used to match elements based on their position among the group of siblings, counting from the end. 

Syntax:

:nth-last-child(number) {
    //CSS Property
}

Where number is the argument that represents the pattern for matching elements counting from the end. It can be odd, even or in a functional notation.

  • odd: It represents elements whose position is odd in a series: 1, 3, 5, etc., counting from the end.
  • even: It represents the elements whose position is even in a series: 2, 4, 6, etc., counting from the end.
  • functional notation (<An+B>): It represents elements whose position of siblings matches the pattern An+B, for every positive integer or zero value of n. The index of the first element, counting from the end, is 1.

Example 1: In this example every odd element is selected according to formula 2n+1, counting from the end. 

html

<!DOCTYPE html>
<html>
 
<head>
    <title>CSS :nth-last-child Selector</title>
    <style>
        p:nth-last-child(2n+1) {
            background: green;
            color: white;
        }
    </style>
</head>
 
<body style="text-align:center;">
 
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <h2>
        CSS :nth-last-child Selector
    </h2>
 
    <p>
        A computer science portal for geeks.
    </p>
    <p>
        Geeks classes an extensive classroom programme.
    </p>
 
</body>
 
</html>

                    

Output: nlastchild Example 2: 

html

<!DOCTYPE html>
<html>
 
<head>
    <title>CSS :nth-last-child Selector</title>
    <style>
        table {
            border: 1px solid green;
            margin: auto;
        }
 
        /* Selects the last three element */
        tr:nth-last-child(3) {
            background-color: green;
            color: white;
        }
    </style>
</head>
 
<body style="text-align:center;">
 
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <h2>
        CSS :nth-last-child Selector
    </h2>
 
    <table>
        <tbody>
            <tr>
                <td>Merge sort</td>
            </tr>
            <tr>
                <td>Quick sort</td>
            </tr>
            <tr>
                <td>Insertion sort</td>
            </tr>
            <tr>
                <td>Selection sort</td>
            </tr>
        </tbody>
    </table>
 
</body>
 
</html>

                    

Output:

 nlastchild 

Supported Browsers: The browser supported by :nth-last-child selector are listed below:

  • Apple Safari 3.1
  • Google Chrome 4.0
  • Edge 12.0
  • Firefox 3.5
  • Opera 9.0


Last Updated : 05 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads