2 minutes February 21, 2025

How to Select a Parent Div Based on Its Immediate Child Using CSS?

Styling parent elements based on their children has traditionally been impossible with CSS alone, often requiring JavaScript solutions. We can finally achieve this using pure CSS with the modern :has() pseudo-class selector.

Let’s explore how to use this powerful feature to target parent elements based on their immediate children.

Problem 

Many developers face the challenge of selecting a parent element based on its child elements in CSS. Traditionally, this has been impossible with pure CSS alone, as CSS selectors only worked in a forward direction (parent to child). This limitation often forces developers to resort to JavaScript solutions, which add more weight to the project and affect performance.

Solution

Thanks to the modern CSS :has() pseudo-class selector, we can now select parent elements based on their children using pure CSS. This feature is supported in all modern browsers including Chrome 105+, Edge 105+, Safari 15.4+, and Firefox 121+.

Detailed Solution

Using the :has() Selector

The :has() pseudo-class accepts a relative selector list as an argument and selects elements that contain the specified child elements. Here’s how to use it:

Example Implementation

Here’s a practical example of how to use :has() to style a parent div based on its immediate child:

Corresponding HTML:

Browser Support

The :has() selector is supported in:

  • Chrome/Edge (version 105+)
  • Safari (version 15.4+)
  • Firefox (version 121+)

Best Practices

  1. Always check browser support before implementing :has()
  2. Use specific selectors to maintain performance
  3. Test thoroughly across different browsers

Conclusion

The :has() selector provides a powerful way to select parent elements based on their children, solving a long-standing limitation in CSS. While it’s important to consider browser support, this feature enables more maintainable and JavaScript-free solutions for many common UI patterns.

blog
Greetings! I'm Aneesh Sreedharan, CEO of 2Hats Logic Solutions. At 2Hats Logic Solutions, we are dedicated to providing technical expertise and resolving your concerns in the world of technology. Our blog page serves as a resource where we share insights and experiences, offering valuable perspectives on your queries.
Aneesh ceo
Aneesh Sreedharan
Founder & CEO, 2Hats Logic Solutions
Subscribe to our Newsletter
Aneesh ceo

    Stay In The Loop!

    Subscribe to our newsletter and learn about the latest digital trends.