:has
is a parent selector pseudo-class*. It lets you change the parent element properties if it has (:has
) a specific child or a specific element following it.
A CSS pseudo-class is a keyword added to a selector that specifies a special state of the selected element(s). For example,
:hover
can be used to change a button's color when the user's pointer hovers over it.
Here is a simple example of :has
pseudo-class:
.parent:has(.child){
color: blue;
}
What this means is that if the .parent
element contains .child
element, then change the text color of the parent element to blue. This was not possible to implement with css
before. But thanks to :has
selector, now we can add this logic directly in css
and modify .parent
based on what it :has
as a child.
At the time of writing this article
:has
pseudo-class only works in Safari 15.4 and in Chrome Canary. Can i use
Example
I am using a screenshot here so that you don't have to open the codepen in compatible browsers ;)
Empty Button vs Button with an SVG
Instead of having 2 variations of buttons with or without an icon, you can simply use the :has
attribute on the parent.
button:has(svg) {
background: #bd3c91;
}
There is lot more to :has
selector. If you are interested in more usecases, let me know in the comments and i will add more practical usecases.
Top comments (0)