Unlock the Power of CSS :has() Pseudo-Class
Welcome, talented developers! Today, let’s dive into the fascinating world of the :has()
pseudo-class in CSS and explore how it can enhance your web projects. This relatively new feature has been making waves in the frontend community by offering greater control over elements in your UI. Let’s uncover what this pseudo-class is all about and how you can leverage its potential.
Syntax
The :has()
CSS pseudo-class allows you to style an element based on the presence of specific elements within it. It’s like saying, “If this element contains a specific element, then style it in a particular way.” The syntax is straightforward:
:has(<direct-selector>) { /* CSS styles */ }
The :has()
pseudo-class is a powerful tool for targeting elements based on their content.
The Styling Problem
In the past, styling a parent element based on its child or styling one element based on another required JavaScript solutions. With :has()
, this problem is elegantly solved using CSS.
Old School Way – JavaScript
const h1Elements = document.querySelectorAll('h1'); h1Elements.forEach((h1) => { const h2Sibling = h1.nextElementSibling; if (h2Sibling && h2Sibling.tagName.toLowerCase() === 'h2') { h1.classList.add('highlight-content'); } });
This JavaScript snippet illustrates how you would achieve the same effect using JS before the advent of :has()
in CSS.
New School Way – CSS
h1:has(+ h2) { color: blue; }
Throw Some :has() On It!
Now, with :has()
in CSS, you can accomplish the same results as the aforementioned JavaScript function. This CSS snippet targets the direct sibling h2
element following an h1
and changes its color to blue.
:has Selector Example 1
In this scenario, we use :has()
to apply styles to an h1
only if it has a direct h2
sibling.
HTML
<h1>Lorem, ipsum dolor.</h1> <h2>Lorem ipsum dolor sit amet.</h2> <p>Lorem, ipsum dolor sit amet consectetur...</p> <h1>This is a test</h1> <p>Lorem, ipsum dolor sit amet consectetur...</p>
CSS
h1:has(+ h2) { color: blue; }
:has Selector Example 2
In this example, we use :has()
to style an image container with a caption.
HTML
<section> <figure> <img src="dog.jpg" alt="Doggo" /> <figcaption>My Doggo</figcaption> </figure> </section>
CSS
figure:has(figcaption) { background: #c3baba; padding: 0.6rem; max-width: 50%; border-radius: 5px; }
Conclusion
The :has()
pseudo-class in CSS opens up new possibilities for styling and targeting elements based on their contents. By tapping into the power of CSS features like :has()
, we can create sophisticated web interfaces and solve complex styling challenges with elegance.