More Real-World Uses for :has()
I say “more superpowers” because there have already been a ton of really amazing clever ideas published by a bunch of super smart people, like:
When that does happen, you can bet I’ll start using
:has() all over the place. Here are some real-world examples of things I’ve built recently and thought to myself, “Gee, this’ll be so much nicer once
:has() is fully supported.”
I feel like I need to do this kind of thing all the time.
This particular example is a React component I made for a site. I had to “reach outside” the React part of the page with
document.querySelector(...) and toggle a class on the
<header>, or another component. That’s not the end of the world, but it sure feels a bit yuck. Even in a fully React site (a Next.js site, say), I’d have to choose between managing a
menuIsOpen state way higher up the component tree, or do the same DOM element selection — which isn’t very React-y.
:has(), the problem goes away:
Adding alternate row “stripes” to your tables can be a nice UX improvement. They help your eyes keep track of which row you’re on as you scan the table.
But in my experience, this doesn’t work great on tables with just two or three rows. If you have, for example, a table with three rows in the
<tbody> and you’re “striping” every “even” row, you could end up with just one stripe. That’s not really worth a pattern and might have users wondering what’s so special about that one highlighted row.
What to get fancier? You could also decide to only do this if the table has at least a certain number of columns, too:
I often need to change a page layout depending on what’s on the page. Take the following Grid layout, where the placement of the main content changes grid areas depending on whether there’s a sidebar present.
CSS-wise, this is totally fine, of course. But it does make the template code a little messy. Depending on your templating language it can get pretty ugly to conditionally add a bunch of classes, especially if you have to do this with lots of child elements too.
Contrast that with a
Honestly, that’s not a whole lot better CSS-wise. But removing the conditional modifier classes from the HTML template is a nice win if you ask me.
That’s because the specificity of
:has() is based on the most specific element in its argument list. So, if you have something like an ID in there, your selector is going to be tough to override in the cascade.
If you need help creating a digital marketing strategy for your business, don’t hesitate to contact one of Digidude’s consultants.