Introduction 🚀
The :has() selector is a relational pseudo-class that takes a simple selector list as its argument. It allows you to select an element if it contains at least one element that matches the criteria specified in the argument.
1. Syntax
element:has(selector) {
/* styles */
}
Here, element represents the parent element, and selector specifies the criteria for the child elements.
2. Examples
- Styling a Form Based on Input Fields : Consider a form where you want to highlight the entire form when it contains invalid inputs. You can achieve this with the :has() selector
form:has(input:invalid) { background-color: #ffdddd; }
- Navigational Menus : For a navigation menu, you might want to style a menu item differently if it contains a dropdown menu. Here's how you can do it
nav ul li:has(ul) { font-weight: bold; }
3. Browser support and performance
As of now, the :has() selector is supported in most modern browsers, including the latest versions of Chrome, Firefox, Safari, Edge and Opera. However, it's always a good practice to check for the most current browser compatibility before using new CSS features in production.
While the :has() selector can significantly simplify your CSS and reduce the need for JavaScript, it's essential to use it judiciously. Complex selectors can impact performance, especially on pages with a large DOM. Test and optimize your selectors to ensure they don't cause any noticeable slowdowns.
Conclusion ✅
If you found this article is valuable and useful, share it. 🙏♻