The :nth-last-child
pseudo-class is used to select a group of elements by counting from the end among its sibling elements. It can also be utilized to implement a Quantity Query, applying styles based on the item’s number.
We are going to demonstrate how to use :nth-last-child
with HTML code.
1. Select all even or odd elements counting from the end
Selecting elements whose position numbers are odd or even from the end can be easily achieved by using the keywords odd
or even
.
Tip
You can also use
2n+1
to representodd
and2n
to representeven
.
2. Select the specific element counting from the end
3. Select all elements
We can use n
and n+1
to select all elements, as the last element is labeled as 1, while n
starts from 0.
4. Select all elements before a specific position counting from the end
This notation can be represented as n+b
. It will initially take b
steps and then select all elements starting from the position it has landed.
5. Select elements by patterns counting from the end
This notation can be represented as an+b
. It will initially take b
steps and then select elements every a
steps from the position it has landed.
6. Select the last b elements
By multiplying n
by -1
, it will select all elements in reverse order after b
steps. Therefore, it appears as if selecting the last b
elements.
References