CSS is a powerful language but there are many things it has been unable to do all this while.
However, now, with the introduction of CSS
:has() pseudo-class, it will now be able to perform most of those actions easily.
It is one of the most exciting, rather awaited features introduced in CSS.
So, let’s learn about
According to CSS rules, the child element is targeted based on the parent element (from right to left).
In the following example,
<button> is the targeted element inside the
and CSS property
background: red is applied to
Now, what if we want to target the
<div> element which contains
Well, we can do that now with the help of
The easiest way to describe
:has() is as a parent selector.
If we wish to target the parent element based on the content or the child element we can use
:has() represents an element if the selector passed as parameter matches the element inside
Let’s consider the same example to understand the
In the following example, using the
:has() selector, we are targeting the
<div> element that has the
<div> is the targeted element
<button> is the selector,
which means CSS property
background:red is applied to
<div> only if it contains
Real world scenario
So, let’s say we have a list of products and some of the products are available with offers. Suppose we want to apply some extra style to products with offers.
and simplify the above code by using
Here, if the selector
button.offer passed as a parameter matches the element inside
only then the above CSS is applied.
Product 3 matches this condition, as shown in the image below.
:has() works like magic, there are some restrictions.
- We can’t
- We can not use psudeo elements within
- Use of
:visitedwill always be false.
To check the browser compatibility, we can visit this link.
- Currently, only the latest versions of Safari support
:has()selector by default.
- We can enable
:has()on the latest versions of Chrome by enabling the Experimental Web Platform features.
- We can enable
:has()on latest versions of Firefox using
We can follow this link to understand better how to enable :has() in Chrome.