Juha-Matti Santala
Community Builder. Dreamer. Adventurer.

I can :has() cheeseburger

All the most used browsers now support the :has() pseudo-class, which is one of the most exciting additions to CSS in a long time.

Ever since it was announced and added to first builds, I have collected tutorials, blog posts, ideas and use cases from the web so I can share them in this post.

Whenever a new piece of technology or feature lands, there’s often a few artificial examples out there, leaving us wonder what the real-life use cases would be. This hasn’t really been the case with :has as the community immediately started sharing real life examples.

Use-cases from the community

Ahmad Shadeed has written a couple of very good pieces about :has. He wrote CSS :has Parent Selector two years ago when :has was still up and coming. Once the support landed in browsers, he wrote CSS :has() Interactive Guide, a nice interactive experience to learn how the pseudo-class works.

Andy Bell wrote a blog post sharing his real-life use cases for :has(). From that post, I learned that there’s a :target pseudo-class that selects the element targeted by a fragment in the URL (like http://www.example.com/index.html#section2).

Wes Bos of Syntax.fm originally tweeted a collection of use cases, then discussed them in a podcast and CJ made a Youtube video about them. It’s a solid collection of the base cases. In it, they have examples for styling parents based on the type of elements children are, an anywhere selector (which I really like myself) that allows styling an element based on for example a checkbox being checked somewhere else in the site and a great list of others.

Jim Nielsen shared a use case for disabling background scrolling in case of an open dialog in Mastodon. Robb Owen has also written about locking scroll with :has. Michelle Barker wrote about how to animate grid tracks with :has.

Tobias Ahlin Bjerrome has a nice post about selecting previous siblings. In it, he provides examples for choosing the immediate previous sibling, any nth previous sibling, all previous siblings and all but the immediate previous sibling, making the post a great one-stop shop for all the needs. This sibling selector seems to be a very popular use case as it was also mentioned in aforementioned collections of Andy Bell and Wes Bos.

Noah Liebman’s A progressively enhanced, accessible radio button using Web Components and :host(:has(🤯)) is a worthy read as well for those who are using (or planning to use) Web Components.

Are there other great resources I’ve missed? Join the discussion in Mastodon and share your tips with my readers!

(The title of the post is a reference to the I can haz cheezburger meme.)


Comment by replying to this post in Mastodon.

Loading comments...

Continue discussion in Mastodon »

Syntax Error

Sign up for Syntax Error, a monthly newsletter that helps developers turn a stressful debugging situation into a joyful exploration.