The :has() selector enables styling parent elements based on their children, finally bringing the "parent selector" to CSS. Here's how to use it.
Basic Syntax
Form Validation
Card Layouts
Navigation States
Table Styling
Sibling Selection
Quantity Queries
Dark Mode Detection
Modal and Overlay
Accordion/Disclosure
Empty States
Filter UI
Responsive Behavior
Complex Combinations
Performance Tips
Best Practices
Use Cases:
✓ Parent styling based on children
✓ Form validation states
✓ Dynamic layouts
✓ Sibling relationships
✓ State-based styling
Performance:
✓ Be specific with selectors
✓ Use direct child (>) when possible
✓ Combine with class selectors
✓ Avoid overly broad :has()
Patterns:
✓ Form group validation
✓ Card content detection
✓ Navigation active states
✓ Empty/loading states
Browser Support:
✓ Check caniuse.com
✓ Provide fallbacks
✓ Use @supports for detection
✓ Progressive enhancement
Conclusion
The :has() selector revolutionizes CSS by enabling parent selection based on descendants. Use it for form validation styling, dynamic layouts based on content, navigation states, and quantity queries. Combine with :not() for inverse selection and be mindful of performance by keeping selectors specific. This powerful selector eliminates many JavaScript-based styling solutions while keeping styles declarative and maintainable.