CSS adjacent siblings selector by barbajoe

posted on: Mar 2, 2024

TLDR: :has is awesome-sauce

CSS has been gaining more functionality than JS has over the past few years, and with that has come a LOT of improved developer experience and functionality. This article outlines quite a few tricks that :has now makes trivial, but the one that caught my eye was the previous sibling selector. I wasn't aware this was previously impossible, but I confirmed it after rooting around on MDN . And after a little bit of playing around I've created this example of a radio group that highlights the selected item and its adjacent siblings.

I did need to use JS to set the class of the selected item as CSS does not currently allow you to nest :has but the rest of the complexity is pure CSS.

The important parts of my example are using the next sibling selector (+) to get the immediate next sibling, and using :has to find the previous sibling. Like so:

label.checked + label and label:has(+ label.checked)

Is this useful for anything that I'm currently working on? Nope. Will it ever be helpful for anything that I'll work on? 🀷

Is it awesome sauce? Oh yeah!

Quick Links: