Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

:nth-of-type() — position among elements of the same type

The :nth-of-type() pseudo-class selects an element by its position among siblings of the same type, rather than among all element siblings. It supports 1-based positions, An+B formulas, and the keywords odd and even.

Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required

Syntax

E:nth-of-type(An+B)
E:nth-of-type(odd)
E:nth-of-type(even)
E:nth-of-type(2)

:nth-of-type() counts element siblings of the same type, meaning the same local name and namespace. Counting starts at 1; other element types do not affect the position. p:nth-of-type(2) selects the second p, not necessarily the second child.

In An+B, coefficients A and B are integers, and n takes values 0, 1, 2, …; only positive positions match. 2n+1 and odd mean odd positions, 2n and even mean even positions, -n+3 means the first three, and 2 means only the second.

A class does not define the counted type: .item:nth-of-type(2) tests the second position within the element's type, not among .item elements. Use :nth-child(2 of .item) for the latter. Plain :nth-child(2) counts all element siblings. :nth-of-type() does not accept an of clause.

Examples

<!doctype html>
<meta charset="utf-8">
<title>:nth-of-type()</title>
<style>
  #demo > p:nth-of-type(2) { color: rgb(255, 0, 0); }
</style>
<div id="demo">
  <p>A</p>
  <span>X</span>
  <p>B</p>
  <p>C</p>
</div>
<pre id="result"></pre>
<script>
  const matches = document.querySelectorAll('#demo > p:nth-of-type(2)');
  document.getElementById('result').textContent =
    Array.from(matches, element => element.textContent).join(', ');
</script>

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.

Sources