CSS: :has descendant selector
Check if an element have certain children
tag:has(s1, s2, etc)-
match tag if it contains descendant s1 or s2 etc.
s can be simple selector, compound selector or complex selector.
tag is optional. It can be a simple selector (selecting by tag name, id, class etc) or a compound selector (combination of tag name, id, class etc). If empty, it means the universal selector (* any tag).
/* highlight sections that has h2 */ section:has(h2) { background: pink; }
Example. Invalid field in form
/* highlight invalid field in form */ form:has(input:invalid) { border: 2px solid red; }
Example. checked checkbox
/* strike out line that has checked checkbox, for todo */ 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; }
🟢 TIP: :has is slow
:has() can be slower than other selectors because it looks at descendants. Avoid on very broad selectors like the universal selector.
browser support
the selector :has() are supported by all major browsers since 2024.
CSS Selector. pseudo-class functions
CSS. Selectors
Selector types
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
Nesting syntax
Special selector
- CSS: :root selector
- CSS: no child selector
- CSS: first child, last child, only child selectors
- CSS: nth-child selector
- CSS: nth-child arg of selector
- CSS: nth-of-type selector
- CSS: pseudo-class selector (:)
- CSS: pseudo-element selector (::)
- CSS: negation selector (:not)
- CSS: :has descendant selector