🔍
:has() Selector
Select parent/sibling by child condition
Parent selectors were long impossible in CSS. With :has(), you can now style parent elements based on the presence or state of child elements. This means complex state-based UI can be implemented without JavaScript.
For example, form:has(input:invalid) highlights entire forms with invalid inputs, and .card:has(img) applies different layouts only to cards containing images.
How to Apply
1
Write selectors in parent:has(child-condition) format
2
Combine other pseudo-classes inside :has() (:checked, :focus, :invalid, etc.)
3
Use with sibling combinators (+ or ~) for sibling-based selection
4
Replace JavaScript-based state styling with :has()
Pros
- ✓ Enables state-based styling without JavaScript
- ✓ Complex conditional design achievable with CSS alone
Cons
- ✗ Complex :has() selectors may impact performance
- ✗ Long selectors can reduce readability
Use Cases
Interactive UI changing card styles based on checkbox state
Highlighting entire form when required fields are empty