Yes, we know we’re a bit late to the party, what with the :has()
selector making the rounds of web design and development headlines. But better late than never, right? So let’s dive into this new feature of CSS and see what it’s all about!
Your Web Designer Toolbox
Unlimited Downloads: 500,000+ Web Templates, Icon Sets, Themes & Design Assets
The CSS :has()
selector is a type of complex selector that allows you to select an element based on whether it contains a certain other element. This selector is a powerful tool that can be used in a variety of ways to create advanced styles for your website. Here are some examples of the advanced uses of the :has()
selector:
Selecting Parent Elements with a Specific Child Element
One of the most common uses of the :has()
selector is to select parent elements based on the presence of a specific child element. For example, if you want to select all the li
elements that contain an a element, you can use the following code:
li:has(a) { background-color: yellow; }
Selecting Sibling Elements
Another advanced use of the :has()
selector is to select sibling elements based on the presence of a specific child element. For example, if you want to select all the td
elements that are siblings of a td
element that contains an a element, you can use the following code:
td:has(a) + td { background-color: yellow; }
Selecting Grandparent Elements
You can also use the :has()
selector to select grandparent elements based on the presence of a specific child element. For example, if you want to select all the ul
elements that are grandparent elements of an li
element that contains an a element, you can use the following code:
ul:has(li:has(a)) { background-color: yellow; }
Selecting Elements with Multiple Children
The :has()
selector can also be used to select elements based on multiple children. For example, if you want to select all the p
elements that contain both an em
and a strong
element, you can use the following code:
p:has(em) :has(strong) { background-color: yellow; }
Selecting Elements with Specific Attributes
Finally, you can use the :has()
selector to select elements based on the presence of specific attributes. For example, if you want to select all the input
elements that have a required attribute, you can use the following code:
input:has([required]) { background-color: yellow; }
These are just a few examples of the more complex uses of the :has()
selector. With its powerful syntax, it can be used to make complex selections that would otherwise be difficult or impossible to achieve with traditional selectors.
It’s important to note that the :has()
selector is not supported in all browsers, so it’s always a good idea to check the browser compatibility before using it in a production environment.
This post may contain affiliate links. See our disclosure about affiliate links here.