Codectionary / Developer documentation / CSS

:has() - The Parent Selector

:has() matches an element if any of the selectors passed to it match something within it - effectively letting you style a parent based on its children or descendants, something CSS could never do natively before. It has broad, mainstream browser support as of 2026 and is safe to use in production.

Syntax

:has(selector)

Examples

Styling a Parent Based on Its Children

Highlighting a form group only if it contains an invalid input.

.form-group:has(input:invalid) {
  border-left: 3px solid red;
  background: #fef2f2;
}

Conditional Layout Based on Content

Changing a card's layout depending on whether it contains an image.

.card:has(img) {
  grid-template-columns: 100px 1fr; /* image + text layout */
}

.card:not(:has(img)) {
  grid-template-columns: 1fr; /* text-only layout */
}

Sibling-Based Styling

A powerful combination: styling an element based on the state of a sibling.

.field:has(+ .error-message) input {
  border-color: red; /* highlights an input if an error message follows it */
}

Parameters and values

  • :has(selector) (pseudo-class): Matches if the given selector matches anything inside the element

Best practices

  • Use :has() to replace many patterns that previously required JavaScript, like styling a form field based on its own validity state
  • Combine :has() with :not() to style elements that specifically lack certain children
  • Keep :has() selectors reasonably simple - deeply nested conditions can become hard to reason about, even though they are valid
  • Use :has() for genuinely conditional styling based on content structure, not as a general replacement for simple class-based styling

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation