CSS: :has descendant selector

By Xah Lee. Date: . Last updated: .

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
Simple selectors
Combinators
Selector list
Special selector
Misc