:has() Relational Selector

The :has() pseudo-class allows a selector to match an element based on descendants or relative conditions. It enables patterns that historically required JavaScript or additional classes.

For example, a form field can be styled when it contains an invalid input.

:has() Relational Matching
Parent Based on Child State
.field:has(input:invalid) {
  border-color: #dc2626;
}

.card:has(img) {
  padding-top: 0;
}
💡 The parent is selected based on whether a relative selector matches inside it.
Key Takeaways
  • :has() enables parent-aware styling.
  • It can remove some JavaScript or state-class requirements.
Knowledge Check

What makes `:has()` powerful?