CSS :nth-last-of-type(n)
selector selects every element that is the nth child of its type within its parent, but counting from the last. This selector is just the opposite of the :nth-of-type() selector.
The value n in the :nth-last-of-type(n)
selector can be a:
- Number – Like 1, 2, 3, 4, …
- Keyword – Like
even
&odd
- Formula – Like (2n + 1), (2n + 2), (3n + 1), etc.
Unlike the :nth-last-child() selector, the :nth-last-of-type() selector selects every nth element of its type counting from the last.
For example, If you use :nth-last-of-type(3)
, it would select every third element of its type counting from the last. It means, this third element can be a <p>
, <div>
, <ul>
, <li>
, etc.
See this working example:
Example:
:nth-last-of-type(3){ background: yellow; }
If you want to select the nth last element of a specific type only, you can do this by simply preceding the :nth-last-of-type() selector with the type of the element.
For example, if you want to select the 3rd last element of type <p>
, you have to use p:nth-last-of-type(3)
.
Here is an example:
Example:
p:nth-last-of-type(3){ background: yellow; }
You can also use keywords like even
& odd
to select elements that are at even and odd positions counting from the last.
In the following example, the :nth-last-of-type()
selector sets a yellow background color to the <p>
elements that are at odd positions and sets a cyan color background to the <p>
elements that are at even positions.
Example:
p:nth-last-of-type(odd){ background: yellow; } p:nth-last-of-type(even){ background: cyan; }
The :nth-last-of-type()
selector is not just limited to numbers or keywords. You can even use a formula in the form of (an + b) and select all the matching elements.
For example, If you use (2n + 0), it would select elements whose indexes are a multiple of 2 i.e. Elements at positions 2, 4, 6, 8, … and so on. But remember, these indexes must be counted from the last.
Similarly, If you use (2n + 1), it would select elements that are at positions 1, 3, 5, 7, … and so on counting from the last.
See this example for clarification:
Example:
p:nth-last-of-type(2n+1){ background: yellow; } p:nth-last-of-type(2n+0){ background: cyan; }
CSS Syntax
The syntax of the :nth-last-of-type()
selector is as follows:
:nth-last-of-type(n){ CSS Styles; }
Browser Support
The number in each cell of the table specifies the first version of the browser that fully supports the :nth-last-of-type()
selector.
Selector | |||||
:nth-last-of-type() | 4.0 | 9.0 | 3.5 | 3.2 | 9.6 |