Elijah Mills
WordPress | Web | More

Exploring the :has pseudo-class and smart CSS rules.

Today, I want to share a concept in CSS that I've been toying with. It's something not commonly discussed, but it has captured my imagination. Is it a brilliant idea or a step too far? I'm not entirely sure yet, which is why I'm eager to share this with you and hear your thoughts.

Introducing Contextual Styling with ':has'

Let me take you straight into it. It revolves around the ':has' CSS relational pseudo-class. This feature is gaining traction in terms of support globally, and it’s about time we start making real use of it. The core idea is simple yet potentially groundbreaking: style your content based on its context. Imagine a section in your HTML being styled differently based on the elements it contains - that's what I'm experimenting with.

This approach could fundamentally change how we approach CSS. Instead of relying on a myriad of classes, BEM, or utility classes, we could let our HTML structure dictate the styling. This is not just about making our CSS cleaner or more intuitive; it's about making it smarter.

I tested this concept, focusing on how different compositions of sections could lead to varied styling outcomes. For instance, a section with an h1 element can be styled distinctly from one with a p + h1 pattern. It’s fascinating to see how just by changing the composition of elements, we can trigger different styling rules without touching a single class.

The Potential and The Pitfalls

I'm fully aware this method comes with its challenges. Figuring out the 'recipes' for each section or component can be tricky. Plus, this might not be a one-size-fits-all solution, especially for environments where pre-defined structures don't make sense. But for those of us who write HTML directly, this could be a handy trick.

The big picture I’m envisioning is a CSS framework that’s based on these smart selectors. A system where the content of a container decides its style, with flexibility to accommodate optional elements. This could lead to a more natural way of writing HTML and CSS - more organic, less forced.

Copyright © 2024 Elijah Mills