DEV Community

Cover image for The :has() Selector: Bringing Real Logic to CSS
smrpdl1991
smrpdl1991

Posted on

The :has() Selector: Bringing Real Logic to CSS

“If” logic in CSS — yes, it’s real.

We’ve all said:
“CSS can’t do logic.”

Turns out… that’s not true.

With :has(), CSS can behave like an if condition — letting you style an element based on what it contains or what’s happening inside it.

Example:

/* If a card has an image, add a border */
.card:has(img) {
 border: 2px solid hashtag#4f46e5;
}
Enter fullscreen mode Exit fullscreen mode

In simple terms:
If a .card contains an img ,then apply the style.

Why this matters:
• Less JavaScript to manage UI state
• More reactive, intelligent layouts
• Cleaner, simpler component logic

Top comments (0)