CSS :nth-last-of-type() Pseudo Class
The :nth-last-of-type() CSS pseudo-class selects the elements starting from the last element upwards. Read about the pseudo-class and try examples.
The :nth-last-of-type() pseudo-class selects elements based on their index starting from the last element upwards.
The :nth-last-of-type() can be specified by a number, a keyword, or a formula.
| Value | Description |
|---|---|
number | Matches the exact nth element from the end. |
odd / even | Matches elements at odd or even positions from the end. |
an + b | Matches elements at positions calculated by the formula an + b, where a and b are integers and n is a counter starting from 0. |
The :nth-last-of-type() pseudo-class is similar to :nth-of-type() but there is a difference: it counts the items from the end whereas :nth-of-type() counts them from the beginning.
This pseudo-class is also similar to :nth-last-child, but they differ in what they match: :nth-last-of-type() targets a specific element type among its siblings, while :nth-last-child() matches any element type at the given position. Both have identical specificity.
Version
Syntax
CSS :nth-last-of-type() syntax
:nth-last-of-type( <nth> ) {
css declarations;
}Example of the :nth-last-of-type() pseudo-class:
CSS :nth-last-of-type() code example
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p:nth-last-of-type(3) {
background: #8ebf42;
}
</style>
</head>
<body>
<h2>:nth-last-of-type() selector example</h2>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
<p>Paragraph 5</p>
<p>Paragraph 6</p>
</body>
</html>Example of the :nth-last-of-type() pseudo-class with "odd" and "even":
CSS :nth-last-of-type() another code example
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p:nth-last-of-type(odd) {
background: #1c87c9;
color: #eeeeee;
}
p:nth-last-child(even) {
background: #666666;
color: #eeeeee;
}
</style>
</head>
<body>
<h2>:nth-last-of-type selector example</h2>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
<p>Paragraph 5</p>
<p>Paragraph 6</p>
</body>
</html>Example of the :nth-last-of-type() pseudo class with a formula (an + b):
HTML/CSS Example of the :nth-last-of-type() pseudo class with a formula (an + b)
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p:nth-last-of-type(3n+0) {
background: #767fea;
padding: 10px;
color: #ffffff;
}
</style>
</head>
<body>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
<p>The fifth paragraph.</p>
<p>The sixth paragraph.</p>
<p>The seventh paragraph.</p>
<p>The eight paragraph.</p>
<p>The ninth paragraph.</p>
</body>
</html>Practice
What is the function of the :nth-last-of-type CSS pseudo-class?