DEV Community

Cover image for Now CSS Has :has(),The Mind-blowing Feature
Sampad Sarker
Sampad Sarker

Posted on

Now CSS Has :has(),The Mind-blowing Feature

One of the most-awaited features in CSS is :has() functional pseudo-class. It is a level 4 CSS selector.

The :has() checks whether an element has a particular child element or group of child element in its arguments and based on that a certain style is applied.

On Which Part of :has(), Style Will Be Applied ?
The :has() is more than a parent selector. It is very important to understand which element should be styled by :has().

section:has(article) { … }--> "section" element will be styled.
section:has(article) img { … }--> "img" element will be styled, not "section" element.

Few Property of :has()
1.The selector list of :has() is forgiving.
2.The specificity of :has() is that of its most specific argument like :is().

Let's take a deep dive🀿 to demystify the :has()

Selecting Parent Element
The default behaviour ofΒ :has() is to select the parent.
Example code
Image description

Image description

Selecting Child Element
Selecting the child or direct child.
Example code
Image description

Image description

Grouping of Multiple Children
Selecting more than one child at a time.
Example code
Image description
Image description

Selecting the Previous Sibling Element
Selecting the Previous Sibling Element is possible by combined use of CSS adjacent sibling combinator with the :has().
Example code
Image description

Image description

Conditional Decorations
Based on child element under any condition, different style can be applied.
Example code
Image description

Image description

Styling Empty States
It is possible to style elements that contain nothing using :empty and :has() together very easily.
Example code
Image description

Image description

Layout Customize
Layout can be changed according to child element with or without condition.
Example code
Image description

Image description

Change Theme Without Js
Theme mood toggle Without JS, it is possible now for the pseudo-class ":has()". You should thank this CSS feature, shouldn't you?
Example code
Image description

Image description

Browser Support Check
At the time of publishing this post, the :has() achieves global 76.16% of browser support. Few browser didn't adopt it(Firefox is one of them 😟).I hope, it will be supported 100% by all browsers.
Example code
Image description

Image description

Caution
⚠ The :has() pseudo-class can not be nested within another :has().
⚠ The :has() does not take any pseudo-elements in its argument.

All examples' live code here‡

Thanks for reading all the way through πŸŽ‰πŸ₯³πŸŽˆ.
I hope you learned something new from this post. Feel free to leave your comments, advice, and suggestions so that I'll publish better posts in the future.

Top comments (0)