CSS: :has descendant selector

By Xah Lee. Date: . Last updated: .

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
Combinators
Selector list
Nesting syntax
Special selector
Misc