:has() - The Parent Selector
You'll learn how to select parent elements based on what's inside them — something previously impossible in CSS.
For years, CSS could only select "downward" (parents targeting children). If you wanted to style a card differently when it contained an image, you were out of luck. The :has() pseudo-class changes everything by letting you select elements based on their descendants.
How It Works
Think of :has() as asking a question: "Does this element have something inside it?"
/* Select any <article> that contains an <img> */
article:has(img) {
border: 3px solid blue;
}
Here, the article gets styled only if it has an img somewhere inside.
True Parent Selection
You can now style parents based on child state:
/* Style a form differently if any input is focused */
form:has(input:focus) {
background-color: lightyellow;
}
/* Style a card that contains a "sale" badge */
.card:has(.sale-badge) {
border-color: red;
}
Sibling Selection Too
:has() even works with sibling combinators:
/* Select an h2 that's immediately followed by a paragraph */
h2:has(+ p) {
margin-bottom: 0.5rem;
}
Combining with Other Selectors
Since you've learned :is() and :where(), you can combine them:
/* Select any section containing either a video or an image */
section:has(:is(video, img)) {
padding: 2rem;
}
Key Takeaway: :has() lets you select elements based on what they contain or what follows them, finally enabling true parent and context-aware styling in CSS.