Why does a CSS selector match more elements than I expected?
Quick answer
Start with the selector’s rightmost part, then check each candidate element against the relationships to its left. A space allows a descendant at any depth; > requires a direct child. + selects the immediately following sibling, while ~ can select later siblings with the same parent. A comma separates alternatives, so an element need only match one branch. [S1] [S2]
The question, the details, the next step.
A practical checklist
Start with elements matching the selector’s rightmost part.
Trace each combinator against the actual ancestor, parent, or sibling relationship.
Check comma-separated branches independently, then combine their matches as alternatives.
Record intended and unexpected matches before changing the selector.
Change one relationship at a time and trace again against a reduced HTML example.
A few more useful answers
Does a space in a selector mean direct child?
No. It allows a descendant at any depth. Use > when the matched element must be a direct child. [S1]
Does a comma require an element to match every listed selector?
No. A comma-separated selector list matches an element if it matches at least one branch. [S2]
What is the difference between `+` and `~`?
+ matches the immediately following sibling; ~ can match later siblings with the same parent, whether or not they are adjacent. [S1]
Sources
References used for this guide.
- [S1] CSS selectors and combinators — MDN developer.mozilla.org · Checked
- [S2] CSS selector structure — MDN developer.mozilla.org · Checked
