CKTIS / CSS
:nth-last-of-type() — position among same-type elements from the end
The :nth-last-of-type() pseudo-class selects elements by their position among siblings of the same type, counting from the end.
Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required
Syntax
E:nth-last-of-type(An+B)
E:nth-last-of-type(odd)
E:nth-last-of-type(even):nth-last-of-type() counts same-type elements among siblings, starting at 1 at the end. Type means local name and namespace, not CSS class. Elements of other types and text nodes do not affect this position.
The An+B argument specifies positions for integers n >= 0; only positive results count. 2 means second from the end, odd equals 2n+1, even equals 2n, and -n+2 selects the last two elements of a type. :nth-last-of-type(1) is equivalent to :last-of-type.
Unlike :nth-of-type(), counting proceeds from the end. :nth-last-child() without of counts all element siblings. The of S syntax is not allowed here; .item:nth-last-of-type(2) does not mean the second-to-last element with class .item.
In the example, the selector matches only b: the paragraph order from the end is c, b, a. The span elements are skipped.
Examples
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>nth-last-of-type</title>
<style>
#items > p:nth-last-of-type(2) {
background-color: yellow;
}
</style>
<div id="items">
<p id="a">A</p>
<span>X</span>
<p id="b">B</p>
<p id="c">C</p>
<span>Y</span>
</div>
<script>
const matches = document.querySelectorAll('#items > p:nth-last-of-type(2)');
console.log(Array.from(matches, element => element.id).join(', '));
</script>
</html>Result
b
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.