What it is and why to use it
The of selector clause makes :nth-child count only siblings matching a chosen selector. This differs from selecting an element that both has a class and occupies a position among all children. It is useful when non-item elements are interspersed with a list’s actual items.
Common mistakes and limitations
The of clause requires browser support beyond the oldest :nth-child syntax. Its selector contributes to specificity. If the highlight carries essential meaning, express that meaning in HTML as well rather than relying only on positional styling.
Try the example
The example pairs editable CSS with its own HTML preview. Run it, then change one declaration at a time and compare the result. Locally, put the CSS in a style element in the document head or in an external stylesheet linked from the HTML. Feature support varies by browser and version; use the linked reference and a useful fallback where needed.
HTML used by this example
<div><p class="row">First item</p><p>A note, not an item</p><p class="row">Second item</p><p class="row">Third item</p></div>Syntax
:nth-child(2 of .item) { ... }Examples
Filtered Counting with :nth-child of
Run the CSS against the supplied HTML, then experiment with the values.
.row { padding: .5rem; }
.row:nth-child(2 of .row) { background: #dbeafe; color: #172b4d; border-inline-start: 4px solid #2563eb; }- Only siblings matching .row participate in the filtered count.
- The highlighted second .row is the third child overall because a note appears before it.
- Compare with .row:nth-child(2), which counts all element siblings. This is useful when styling results mixed with headings or explanatory rows.
HTML used by this example
<div class="demo"><div><p class="row">First item</p><p>A note, not an item</p><p class="row">Second item</p><p class="row">Third item</p></div></div>Best practices
- The of clause requires browser support beyond the oldest :nth-child syntax. Its selector contributes to specificity. If the highlight carries essential meaning, express that meaning in HTML as well rather than relying only on positional styling.
- Inspect the relevant browser reference and test the browsers used by your audience.
Runtime & versions
Web browsers. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
CSS specifications (modules)