DEV Community

Joefrey Mahusay
Joefrey Mahusay

Posted on

:has() pseudo-class

As of my last knowledge update in January 2022, the :has() pseudo-class is not part of the CSS standard, and it's not widely supported by browsers. However, there have been discussions and proposals related to this pseudo-class, particularly in the context of Selectors Level 4.

The :has() pseudo-class is intended to allow the selection of an element based on whether it contains a specific selector. Here's a hypothetical example of how it could be used in a real-world scenario once it's supported:

CSS Code

p:has(a) {
  background-color: lightblue;
  padding: 20px;
  border-radius: 7px;
  font-family: 'Arial', sans-serif;
  font-size: 1rem;
  line-height: 1.5rem;
}
p a {
  color: tomato;
}
Enter fullscreen mode Exit fullscreen mode

HTML Code

<p>Convert px to rem with <a href="https://plexcalc.com/">Plexcalc.com</a> Fast and Accurate Online Calculator and Converter. Lorem ipsum dolor sit, amet consectetur adipisicing elit. </p>
Enter fullscreen mode Exit fullscreen mode

In this example, the :has(a) selector is used to select

elements that contain an <a> (anchor) element. When this pseudo-class becomes widely supported, it could provide a more concise way to select elements based on their content.

As of now, developers typically use JavaScript or other scripting languages to achieve similar effects, dynamically selecting and styling elements based on their content or the presence of specific child elements. The lack of widespread support for :has() in CSS has led to the reliance on JavaScript for such tasks in real-world scenarios.

Keep in mind that browser support for new CSS features can change over time, so it's a good practice to check the latest specifications and browser compatibility tables to see if there have been updates since my last knowledge update in January 2022.

Top comments (0)