DEV Community

Kevin Ramirez
Kevin Ramirez

Posted on

Unleashing the Power of :has() in CSS: A Selective Journey✨

🚀 Hey Dev Community! Have you ever found yourself wishing CSS had a more robust way to select elements based on their content or structure? Well, your developer dreams are about to come true with the lesser-known :has() pseudo-class! 🎉

Understanding the Magic of :has()

The :has() pseudo-class introduces a new level of selectivity to CSS, enabling you to target elements based on their descendants. This opens the door to more precise styling, reducing the need for complex class names or additional HTML structure.

Let's dive into some examples:

<body>
  <div>
    <a href="#">I'm a link inside a div!</a>
  </div>

  <ul>
    <li class="special">Special List Item</li>
    <li>Ordinary List Item</li>
  </ul>

  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed cursus purus vitae tellus sodales.</p>

  <p>This paragraph is empty.</p>
</body>
Enter fullscreen mode Exit fullscreen mode
/* Selecting a div containing an anchor tag */
div:has(a) {
  border: 2px solid #3498db;
  padding: 10px;
}

/* Styling a list item with a specific class */
li:has(.special) {
  background-color: #ffcc00;
  font-weight: bold;
}

/* Applying styles to paragraphs with more than 100 words */
p:has(:not(:empty):after) {
  color: #2ecc71;
  font-style: italic;
}
Enter fullscreen mode Exit fullscreen mode

Breaking Down the Examples

  1. Selecting a div containing an anchor tag: The div:has(a) rule adds a border and padding to any div that contains an anchor (a) tag.
  2. Styling a list item with a specific class: The li:has(.special) rule applies styles to list items with the class special, making them stand out.
  3. Applying styles to paragraphs with more than 100 words: The p:has(:not(:empty):after) rule targets paragraphs with content (not empty) and more than 100 words, applying a unique style.

Conclusion

The :has() pseudo-class is a powerful tool in the CSS arsenal, offering a more expressive way to style elements based on their internal structure. As you experiment with this feature, share your thoughts, creative use cases, and any cool discoveries below! 👇

Top comments (0)