Selectors used to look only down and forward: the subject of .card img is the image. :has() lets the subject depend on what's around it. Its argument is a relative selector, which starts with an implied or explicit combinator, anchored at the element being tested:
.card:has(img): a card containing an image anywhere (descendant)..card:has(> img): a card with an image child.h2:has(+ p): a heading immediately followed by a paragraph, which is previous-sibling selection.h2:has(~ .note): a heading with any later sibling.note.
It works with state, so styles can react to the inside of a component with no JavaScript: form:has(:invalid), label:has(+ input:invalid), html:has(#dark:checked). Quantity queries become simple too: ul:has(> li:nth-child(4)) matches lists with four or more items.
Limits, all in Selectors 4:
- No nesting:
:has()isn't valid inside:has(), even wrapped in:is()or:not(). - No pseudo-elements inside it, and it can't follow one (
::before:has(a)is invalid). - Unforgiving list: one unknown selector in
:has(.a, :foo)makes the whole selector invalid, so the rule is dropped. It was forgiving until a 2022 spec change. - Specificity is that of its most specific argument, like
:is():div:has(#target)is (1, 0, 1) and beatdiv.k.l.
Order with :not() matters: section:not(:has(h2)) is a section with no h2; section:has(:not(h2)) is a section with any non-h2 descendant.
:has() also works in JavaScript (querySelectorAll, matches). How engines keep it fast is a browser-internals topic.
Support: Chrome 105, Firefox 121, Safari 15.4.