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
Selecting Child Element
Selecting the child or direct child.
Example code
Grouping of Multiple Children
Selecting more than one child at a time.
Example code
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
Conditional Decorations
Based on child element under any condition, different style can be applied.
Example code
Styling Empty States
It is possible to style elements that contain nothing using :empty and :has() together very easily.
Example code
Layout Customize
Layout can be changed according to child element with or without condition.
Example code
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
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
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)