Filtered nth-child and selector parsing
Definition and purpose
Filtered nth-child first forms a list of siblings matching a selector, then applies the positional formula to that list. This differs from matching a class after counting all element siblings. Indexes start at one.
Second active item
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; font: 16px sans-serif; color: #172033; background: white; } li { color: black; } li:nth-child(2 of .active) { color: green; } </style> </head> <body> <ul> <li id="a" class="active">A</li> <li id="b">B</li> <li id="c" class="active">C</li> <li id="d" class="active">D</li> </ul> </body></html>The second active item is C, not B.
Syntax and mental model
:nth-child(2 of .active) selects the second active sibling. .active:nth-child(2) selects the second sibling only if active. Specificity of filtered nth-child includes its pseudo-class weight plus the maximum specificity of its filter. An ordinary comma-separated selector list is invalid if a selector is invalid; :is() and :where() discard invalid branches of their forgiving lists.
Forgiving and ordinary lists
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; font: 16px sans-serif; color: #172033; background: white; } li { color: black; } #a, :not-a-real-state { color: red; } :is(#c, :not-a-real-state) { color: green; } </style> </head> <body> <ul> <li id="a" class="active">A</li> <li id="b">B</li> <li id="c" class="active">C</li> <li id="d" class="active">D</li> </ul> </body></html>The first rule list is rejected; the valid branch of :is() survives. The unknown pseudo-class is intentionally invalid.
Common mistakes
Do not assume :not(), :has() or the of-filter have forgiving parsing. Use filtered counting for visible groups only if the filter actually expresses which elements to count; display:none alone does not remove an element from sibling counting.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Relational selectors. Next lesson: Shadow DOM and custom states.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Filtered nth-child and selector parsing — knowledge check
Five questions on filtered nth-child and selector parsing.
What is counted by :nth-child(2 of .active)?
What is the first sibling index?
Which has a forgiving selector list?
What happens to an ordinary list containing an unknown pseudo-class?
Does display:none exclude a sibling from ordinary nth-child counting?