It’s been some time since my final article on right here (effectively, a month is some time for me, anyway 😅), as I’ve been busy with my head down getting ready for my discuss on trendy CSS structure at Past Tellerand, which is (checks notes) tomorrow!
Though I haven’t had a lot time for running a blog, it has given me an opportunity to delve as soon as once more into messaging about with CSS structure and the
:has() pseudo-class, or “guardian selector”. I’ve already written about
:has() in a earlier publish, and you may learn an in-depth information by Jen Simmons on the Webkit weblog. However to recap,
:has() permits us to pick out a guardian or sibling of a component by taking a relative selector checklist as its argument (to paraphrase MDN).
However what I’m realising as I proceed to mess around with
:has() is that in apply, we are able to choose any factor within the DOM relative to a different, so long as they share a standard ancestor — which they need to, proper? As any factor that we wish to choose goes to have the
<physique> as its ancestor. This makes it fairly highly effective.
So right here a few demos to that impact. (You’ll have to view these in a browser that helps
:has(), e.g. Chrome or Safari.) On this one, hovering on an inventory merchandise on the left animates our grid tracks on the proper. They share a standard wrapper factor as their ancestor, however they don’t essentially must.
See the Pen
Animated grid tracks with :has() by Michelle Barker (@michellebarker)
On this second demo, we’re including a background color to the
<part> factor focused by a hyperlink in one other
<part> on hover or click on. That is maybe a little bit of a foolish demo, however I can see some potential use circumstances, similar to offering a visible clue for customers as to the focused part of a doc.
See the Pen
Untitled by Michelle Barker (@michellebarker)
Lastly, this demo (finest considered on desktop) opens a panel (utilizing animated grid tracks) when the consumer clicks the hyperlink on the left. The hyperlink’s goal is hidden inside the collapsed panel. (It additionally combines container queries for the content material on the proper.) Hiding and revealing content material is commonly one thing that ought to be finished with JS, and there are seemingly some accessibility points right here — I’m not suggesting you must do something like this in manufacturing. Nevertheless it’s fascinating to see the facility of CSS at present!
See the Pen
Animated grid tracks, :has() + container queries by Michelle Barker (@michellebarker)