css has selector

CSS, Selectors, Modern CSS

Style parent elements based on their children using the :has() pseudo-class selector.

Explanation

  • :has(selector): Selects elements that contain at least one element matching the given selector.
  • :has(> selector): Uses direct child combinator to match only immediate children.
  • :has(+ selector): Matches elements followed by a sibling that matches the selector.
  • Enables “parent selectors” and conditional styling based on content presence.

Usage

To style elements based on their descendants or siblings:

/* Style cards that contain images */
.card:has(img) {
  border: 2px solid blue;
}

/* Style forms with invalid inputs */
.form:has(input:invalid) {
  border-left: 4px solid red;
}

/* Style articles that have both h2 and blockquote */
article:has(h2):has(blockquote) {
  background: #f5f5f5;
  padding: 2rem;
}

/* Style navigation when it has active links */
nav:has(.active) {
  background: var(--primary-color);
}