Using :has() for parent selectors

This is a "Today I Learned" post - a quick note about something I discovered.
Topic: css

Using :has() for parent selectors in CSS

Today I learned about the :has() pseudo-class in CSS, which finally gives us a way to select parent elements based on their children!

The problem it solves

Before :has(), it was impossible to select a parent element based on its children using only CSS. For example, if you wanted to style a container differently when it contained a specific element, you’d need JavaScript.

Basic usage

/* Select any article that contains an image */
article:has(img) {
  padding: 1rem;
}

/* Select any form that contains an invalid input */
form:has(input:invalid) {
  border: 1px solid red;
}

Practical example

Here’s a real-world example: styling a card differently when it contains an image:

.card:has(.card-image) {
  grid-template-rows: min-content 1fr auto;
}

.card:not(:has(.card-image)) {
  grid-template-rows: auto 1fr auto;
}