CSS :nth-last-child

The :nth-last-child() CSS pseudo-class matches elements based on their position among a group of siblings, counting from the last child. It selects elements that match the set of arguments, which is a formula that specifies the pattern of the elements to be selected. This can be helpful when you want to target specific elements towards the end of a parent element.

Syntax:

selector:nth-last-child(n)
{
    property: value;
}

The :nth-last-child() pseudo-class takes a single argument n, which represents the index of the child element from the end. The index starts at 1, not 0, and can be a positive number, 0, or a negative number.

Examples:

Result:

Consider the following HTML structure:

<div class="parent">
    <p>First child</p>
    <p>Second child</p>
    <p>Third child</p>
    <p>Fourth child</p>
    <p>Fifth child</p>
</div>

If we want to select the 2nd and 3rd children from the end:

.parent p:nth-last-child(2),
.parent p:nth-last-child(3)
{
    color: red;
}

This will apply the color red to the "Fourth child" and "Third child" paragraphs.

In the above example, the :nth-last-child(2) selects the second child from the end, which is the "Fourth child," and the :nth-last-child(3) selects the third child from the end, which is the "Third child."

Conclusion:

The :nth-last-child() CSS pseudo-class is a handy tool for selecting elements based on their position relative to the end of a parent element. It allows for dynamic styling of elements depending on their order within the parent container.