:has() CSS Selector : A Powerful Tool for Complex Styling

:has() CSS Selector : A Powerful Tool for Complex Styling

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, FirefoxSafari, 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. 🙏♻

Frequently Asked Questions

What is the :has() CSS selector?

The :has() selector is a relational pseudo-class that selects an element if it contains at least one element matching the selector passed to it, which is why it is often called the parent selector.

Is :has() supported in all browsers?

Yes. As of December 2023 the :has() selector is supported in all major browsers, including Chrome, Edge, Safari and Firefox, and it is now part of Baseline widely available.

Can :has() select a parent element?

Yes. For example, form:has(input:invalid) selects a form that contains an invalid input, letting you style a parent based on its children, which was not possible in CSS before.

What is an example of the :has() selector?

A common example is nav ul li:has(ul) { font-weight: bold; }, which makes a menu item bold only when it contains a submenu.

Does :has() affect performance?

The :has() selector is well optimized in modern browsers and performs fine for typical use, though very broad or deeply nested :has() queries on large pages should be used thoughtfully.