CSS Selector: check descendant (has)

By Xah Lee. Date: .

check if have certain children

the selector :has() are supported by all major browsers since 2024.

e:has(s1, s2, etc)

match e if it contains descendant s1 or s2 etc.

Example 1: Style cards that contain images

.card:has(img) {
 border: solid 1px red;
}

Example 2: Highlight sections with headings

section:has(h2) {
  background: #f8fafc;
  padding: 2rem;
  border-left: 5px solid #3b82f6;
}

Example 3: Advanced – Adjacent siblings

/* Style a form only if it has an invalid field */
form:has(input:invalid) {
  border: 2px solid #ef4444;
  background: #fef2f2;
}

/* Style a list item only if it contains a checked checkbox */
li:has(input[type="checkbox"]:checked) {
  text-decoration: line-through;
  color: #666;
}

Example 4: :has() with :not()

/* Articles without images */
article:not(:has(img)) {
  max-width: 60ch;
}

CSS, Selectors