Relational selectors
Definition and purpose
:has() matches an element when at least one relative selector in its argument matches from that element. It can respond to descendants, children or following siblings without adding a class to the subject.
Parent with badge
<!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; } .card { border: 2px solid black; } .card:has(> .badge) { border-color: green; } </style> </head> <body> <section id="a" class="card"> <h2>Offer</h2> <p class="badge">New</p> </section> <section id="b" class="card"> <h2>Basic</h2> </section> <label id="c" for="x">Accept</label> <input id="x" type="checkbox" checked> </body></html>Only the card with a direct badge gets a green border.
Syntax and mental model
.card:has(> .badge) checks for a direct child; label:has(+ input:checked) checks the immediately following sibling. :has() takes the maximum argument specificity, cannot be nested inside itself, and its argument list is not forgiving. Use @supports selector(:has(*)) for an enhancement, while keeping a usable default.
Adjacent checked input
<!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; } label { color: black; } label:has(+ input:checked) { color: green; } </style> </head> <body> <section id="a" class="card"> <h2>Offer</h2> <p class="badge">New</p> </section> <section id="b" class="card"> <h2>Basic</h2> </section> <label id="c" for="x">Accept</label> <input id="x" type="checkbox" checked> </body></html>The label matches because its next sibling is checked.
Common mistakes
Do not reverse the subject: .card:has(.badge) styles the card, not the badge. Avoid using visual state as the sole indicator of a checkbox value.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Logical pseudo-classes. Next lesson: Filtered nth-child and selector parsing.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Relational selectors — knowledge check
Five questions on relational selectors.
Which element is styled by article:has(img)?
Which checks a direct child?
Which checks an immediately following sibling?
Can :has() directly nest another :has()?
What checks selector support?