CSS: :has descendant selector
Check if have certain children
the selector :has() are supported by all major browsers since 2024.
tag:has(s1, s2, etc)-
match tag if it contains descendant s1 or s2 etc.
tag here is compound selector, or none, which means the universal selector (* any tag).
/* Style cards that contain images */ .card:has(img) { border: solid 1px red; }
/* highlight sections with headings */ section:has(h2) { background: pink; }
Example. Adjacent siblings
/* style a form only if it has an invalid field */ form:has(input:invalid) { border: 2px solid red; } /* style a list item only if it contains a checked checkbox */ li:has(input[type="checkbox"]:checked) { text-decoration: line-through; color: grey; }
Example. :has() with :not()
/* Articles without images */ article:not(:has(img)) { max-width: 60ch; }
:has is slow
๐ข TIP:
:has() can be slower than other selectors because it looks at descendants. Avoid on very broad selectors like the universal selector.
CSS Selector. pseudo-class functions
CSS. Selectors
Selector types
- CSS: types of selectors
- CSS: simple selectors
- CSS: compound selectors
- CSS: complex selector (combinator)
Simple selectors
- CSS: type selector (tag name)
- CSS: universal selector (* any tag)
- CSS: class selector (.x)
- CSS: ID selector (#)
- CSS: attribute selector ([x])
Combinators
- CSS: descendant selector (space)
- CSS: child selector (>)
- CSS: adjacent sibling selector (+)
- CSS: subsequent sibling selector (~)
Selector list
Special selector
- CSS: :root selector
- CSS: no child selector
- CSS: first child, sibling rank selector
- CSS: nth-child selector
- CSS: pseudo-class selector (:)
- CSS: pseudo-element selector (::)
- CSS: negation selector (:not)
- CSS: โis any ofโ selector (:is, :where)
- CSS: :has descendant selector