Practical uses of the :has() relational pseudo class

By Brecht De Ruyte

5 min read

The :has() relational pseudo class has landed in Chrome and Safari and even though it gets less hype than for instance container queries, I believe this little pseudo class contains a lot of improvements to the way we write CSS today.

Practical uses of the :has() relational pseudo class
Authors

Using :has() as a simple parent selector

How many times have we added an extra class to check if an element contains an image, or has some extra information that we want to display. For example, You might want to make a grid where the grid item is shown bigger when it contains an image:

grid with a bigger column when an image is present

Whichever the templating language you’re using. You’ll probably add a condition to check if an image is available like this:

<div class="articles">
  {% for article in articles %}
  <article class="article{% if article.image %} has-image{% endif %}">{# content here #}</article>
  {% endfor %)
</div>

While this works and has worked for many years, there is a fundamental problem with this approach. We are actually using different class names and controlling those with our templating language. Usually adding a class name such as .has-image , but this can lead to inconsistencies when working with bigger teams. For example, another person might prefer to add a class to the grid saying .is-wide based on the availability of the image. Before you know it, those inconsistencies pile up, and the project becomes harder to maintain. With the :has() pseudo class, all of this is in the past as we can check the availability of an image inside of our grid with ease:

article:has(figure) {
  /* do stuff */
}

Here is a full example of that in action

Using :has() and :not() pseudo classes combined

Gandalf in lord of the rings - you shall not pass

Taking the previous grid a step further we might want to display our grid a bit differently when there aren’t any images (figures) available. We can easily do this by combining the :has() and :not() selector. In this use-case I just wanted the “only text grid” to fill the space by using a flex layout instead of grid. So adding the following does just that:

.articles:not(:has(figure)) {
  display: flex;
  flex-wrap: wrap;
  text-align: center;
  border-radius: 10px;
}

.articles:not(:has(figure)) article {
  padding: 40px 20px;
  flex: 1;
  min-width: 280px;
}

Be mindful that the order plays an important role here. For example:

  • .articles:not(:has(figure)) Will target .articles that doesn't have a figure
  • .articles:has(:not(figure)) Will target .articles that has anything in it besides a figure. So an empty .articles would not be targeted in this case

And you can see this in action in this codepen

Changing a list-type based on hover without hassle

It might be something that isn’t as popular as it used to be when it comes to design, but I really implemented a lot of hover states in footer links where the bullet of a list item had to be filled when hovering over it. This usually required adding a pseudo element with absolute positioning. An image says more than a thousand words so let me just show what I’m talking about:

list with active state using the has relational pseudo class

This could be done by creating a simple unordered list and doing something like this:

<ul>
    <li><a href="https://en.wikipedia.org/wiki/Tim_Berners-Lee" target="_blank">Tim Berners-Lee</a></li>
    <li><a href="https://en.wikipedia.org/wiki/Robert_Cailliau" target="_blank">Robert Cailliau</a></li>
    <li><a href="https://en.wikipedia.org/wiki/Vint_Cerf" target="_blank">Vint Cerf</a></li>
    <li><a href="https://en.wikipedia.org/wiki/Bob_Kahn" target="_blank">Bob Kahn</a></li>
</ul>
ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

li {
  margin-block: 6px;
}

a {
  display: flex;
  align-items: center;
  color: #6247aa;
  text-transform: uppercase;
  font-weight: 600;
  text-decoration: none;
}

a::before {
  content: '';
  display: block;
  width: 10px;
  height: 10px;
  margin-inline-end: 10px;
  border: 1px solid #6247aa;
  border-radius: 50%;
}

a:hover,
a:focus {
  color: #a06cd5;
}

a:hover::before,
a:focus::before {
  background: #a06cd5;
  border-color: #a06cd5;
}

But now, let’s enter the :has() pseudo element into the equation and use our default list styles to create pretty much the same thing with less lines of code:

ul {
  list-style: circle;
  margin: 0;
  padding: 0;
}

li {
  margin-block: 6px;
  color: #6247aa;
}

li::marker {
  font-size: 27px;
}

li:has(:hover, :focus-within) {
  list-style: disc;
  color: #a06cd5;
}

a {
  color: currentColor;
  text-transform: uppercase;
  font-weight: 600;
  text-decoration: none;
}

There is a minor drawback here and that is that we won’t be able to add a transition based on the list-style. But it's still a pretty neat thing to do. I just love the fact that this is possible. If you have followed and read some of my articles before then you know that sometimes I like to make things that aren’t completely practical but just fun to do. (For example: My little container query flappy bird).

Form validation messaging with :has() to check invalid states

Forms have never been my favorite thing to style but lately they have become less tedious because of all the possibilities out there (accent-color, appearance, …). Also, open-ui is getting a lot more love from the community and that’s a good thing. I'm really looking forward to getting more control over forms even though I do understand the accessibility and UX concerns.

But let’s get into the validation of forms. Most of the time we had to rely on JavaScript to give us instant feedback when a user is typing something that isn’t allowed. In the previous two examples I’ve shown we can check for elements, states such as hovering of a link which means we can now check for states of our form elements. Watch the demo here for better understanding.

We created an HTML5 input field with a regex validation that only accepts lowercase text. By using the following we can check if the form is invalid:

fieldset:has(:invalid) .feedback {
  opacity: 1;
}

There is something else we should take care of. Because we added the required flag to the input field, an empty field will also be considered invalid and show the error message. We can fix that by checking for placeholder text:

fieldset:has(:placeholder-shown) .feedback {
  opacity: 0;
}

Note: it might be a bit “hacky”. But you could use an empty placeholder with a space in it if you just don’t want placeholder text inside of the element or hide it with CSS.

Creating a tiger striped table based on the number of rows

Another awesome thing we can do is to check the amount of children our parent selector has by combining :nth-child with the :has() pseudo class. For example, I created a table that only shows a tiger striped pattern when it has more than 5 children (or rows…). I love the fact that we can keep this layout decision in CSS, rather than relying on our templating files to add an extra class. We can achieve this by this little bit of code, it's that easy:

table:has(tr:nth-child(5)) tr:nth-child(odd) {
  background: hotpink;
  color: #fff;
}
Tiger striped table based on number of rows

See this in action on codepen.

We’ve only scratched the surface

There are already many examples out there on how to use this new pseudo class and I’m sure many more will follow. This really packs a lot of power and can change the way we handle front-end development in the future.

It :has() been a blast experimenting with this relational pseudo class and I'll sure be playing around with it a lot more.


Upcoming events

  • The Test Automation Meetup

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Test automation is a cornerstone of effective software development. It's about creating robust, predictable test suites that enhance quality and reliability. By diving into automation, you're architecting systems that ensure consistency and catch issues early. This expertise not only improves the development process but also broadens your skillset, making you a more versatile team member. Whether you're a developer looking to enhance your testing skills or a QA professional aiming to dive deeper into automation, RSVP for an evening of learning, delicious food, and the fusion of coding and quality assurance! 🚀🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 First round of Talks 19:45 – 🍹 Small break 20:00 – 📢 Second round of Talks 20:45 – 🍻 Drinks 21:00 – 🙋‍♀️ See you next time? First Round of Talks: The Power of Cross-browser Component Testing - Clarke Verdel, SR. Front-end Developer at iO How can you use Component Testing to ensure consistency cross-browser? Second Round of Talks: Omg who wrote this **** code!? - Erwin Heitzman, SR. Test Automation Engineer at Rabobank How can tests help you and your team? Beyond the Unit Test - Christian Würthner, SR. Android Developer at iO How can you do advanced automated testing for, for instance, biometrics? RSVP now to secure your spot, and let's explore the fascinating world of test automation together!

    | Coven of Wisdom - Amsterdam

    Go to page for The Test Automation Meetup
  • Coven of Wisdom - Herentals - Winter `24 edition

    Worstelen jij en je team met automated testing en performance? Kom naar onze meetup waar ervaren sprekers hun inzichten en ervaringen delen over het bouwen van robuuste en efficiënte applicaties. Schrijf je in voor een avond vol kennis, heerlijk eten en een mix van creativiteit en technologie! 🚀 18:00 – 🚪 Deuren open 18:15 – 🍕 Food & drinks 19:00 – 📢 Talk 1 20:00 – 🍹 Kleine pauze 20:15 – 📢 Talk 2 21:00 – 🙋‍♀️ Drinks 22:00 – 🍻 Tot de volgende keer? Tijdens deze meetup gaan we dieper in op automated testing en performance. Onze sprekers delen heel wat praktische inzichten en ervaringen. Ze vertellen je hoe je effectieve geautomatiseerde tests kunt schrijven en onderhouden, en hoe je de prestaties van je applicatie kunt optimaliseren. Houd onze updates in de gaten voor meer informatie over de sprekers en hun specifieke onderwerpen. Over iO Wij zijn iO: een groeiend team van experts die end-to-end-diensten aanbieden voor communicatie en digitale transformatie. We denken groot en werken lokaal. Aan strategie, creatie, content, marketing en technologie. In nauwe samenwerking met onze klanten om hun merken te versterken, hun digitale systemen te verbeteren en hun toekomstbestendige groei veilig te stellen. We helpen klanten niet alleen hun zakelijke doelen te bereiken. Samen verkennen en benutten we de eindeloze mogelijkheden die markten in constante verandering bieden. De springplank voor die visie is talent. Onze campus is onze broedplaats voor innovatie, die een omgeving creëert die talent de ruimte en stimulans geeft die het nodig heeft om te ontkiemen, te ontwikkelen en te floreren. Want werken aan de infinite opportunities van morgen, dat doen we vandaag.

    | Coven of Wisdom Herentals

    Go to page for Coven of Wisdom - Herentals - Winter `24 edition
  • Mastering Event-Driven Design

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Are you and your team struggling with event-driven microservices? Join us for a meetup with Mehmet Akif Tütüncü, a senior software engineer, who has given multiple great talks so far and Allard Buijze founder of CTO and founder of AxonIQ, who built the fundaments of the Axon Framework. RSVP for an evening of learning, delicious food, and the fusion of creativity and tech! 🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 Getting Your Axe On Event Sourcing with Axon Framework 20:00 – 🍹 Small break 20:15 – 📢 Event-Driven Microservices - Beyond the Fairy Tale 21:00 – 🙋‍♀️ drinks 22:00 – 🍻 See you next time? Details: Getting Your Axe On - Event Sourcing with Axon Framework In this presentation, we will explore the basics of event-driven architecture using Axon Framework. We'll start by explaining key concepts such as Event Sourcing and Command Query Responsibility Segregation (CQRS), and how they can improve the scalability and maintainability of modern applications. You will learn what Axon Framework is, how it simplifies implementing these patterns, and see hands-on examples of setting up a project with Axon Framework and Spring Boot. Whether you are new to these concepts or looking to understand them more, this session will provide practical insights and tools to help you build resilient and efficient applications. Event-Driven Microservices - Beyond the Fairy Tale Our applications need to be faster, better, bigger, smarter, and more enjoyable to meet our demanding end-users needs. In recent years, the way we build, run, and operate our software has changed significantly. We use scalable platforms to deploy and manage our applications. Instead of big monolithic deployment applications, we now deploy small, functionally consistent components as microservices. Problem. Solved. Right? Unfortunately, for most of us, microservices, and especially their event-driven variants, do not deliver on the beautiful, fairy-tale-like promises that surround them.In this session, Allard will share a different take on microservices. We will see that not much has changed in how we build software, which is why so many “microservices projects” fail nowadays. What lessons can we learn from concepts like DDD, CQRS, and Event Sourcing to help manage the complexity of our systems? He will also show how message-driven communication allows us to focus on finding the boundaries of functionally cohesive components, which we can evolve into microservices should the need arise.

    | Coven of Wisdom - Utrecht

    Go to page for Mastering Event-Driven Design

Share