Exploring :has() Again

It’s been a while since my last article on here (well, a month is a while for me, anyway 😅), as I’ve been busy with my head down preparing for my talk on modern CSS layout at Beyond Tellerand, which is (checks notes) tomorrow!

Although I haven’t had much time for blogging, it has given me a chance to delve once again into messaging about with CSS layout and the :has() pseudo-class, or “parent selector”. I’ve already written about :has() in a previous post, and you can read an in-depth guide by Jen Simmons on the Webkit blog. But to recap, :has() allows us to select a parent or sibling of an element by taking a relative selector list as its argument (to paraphrase MDN).

But what I’m realising as I continue to play around with :has() is that in practice, we can select any element in the DOM relative to another, as long as they share a common ancestor — which they should, right? As any element that we want to select is going to have the <body> as its ancestor. This makes it pretty powerful.

So here a couple of demos to that effect. (You’ll need to view these in a browser that supports :has(), e.g. Chrome or Safari.) In this one, hovering on a list item on the left animates our grid tracks on the right. They share a common wrapper element as their ancestor, but they don’t necessarily have to.

See the Pen Animated grid tracks with :has() by Michelle Barker (@michellebarker) on CodePen.

In this second demo, we’re adding a background colour to the <section> element targeted by a link in another <section> on hover or click. This is perhaps a bit of a silly demo, but I can see some potential use cases, such as providing a visual clue for users as to the targeted section of a document.

See the Pen Untitled by Michelle Barker (@michellebarker) on CodePen.

Lastly, this demo (best viewed on desktop) opens a panel (using animated grid tracks) when the user clicks the link on the left. The link’s target is hidden within the collapsed panel. (It also combines container queries for the content on the right.) Hiding and revealing content is often something that should be done with JS, and there are likely some accessibility issues here — I’m not suggesting you should do anything like this in production. But it’s interesting to see the power of CSS today!

See the Pen Animated grid tracks, :has() + container queries by Michelle Barker (@michellebarker) on CodePen.

Webmentions for this page

About webmentions

Likes: 40

Reposts: 22

Mentions: 9