Skip to content
Tech News
← Back to articles

The Future of CSS: Target Multiple Classes with the Class Prefix Selector

read original more articles
Why This Matters

The upcoming CSS Class Prefix Selector introduces a streamlined way to target multiple classes sharing a common prefix, simplifying styling workflows and reducing reliance on brittle attribute selectors or extra markup. This feature promises to enhance CSS's flexibility and maintainability, benefiting both developers and end-users by enabling more efficient styling practices. Although still in the specification phase, its adoption could significantly impact how developers manage grouped styles in the future.

Key Takeaways

To target multiple classes that share the same prefix, you’d typically have to resort to brittle attribute selectors or add extra base classes to your markup. To make things easier, CSS is getting a new selector: The Class Prefix Selector ( .prefix-* ).

~

⚠️ This post is about an upcoming CSS feature. You can’t use it … yet. This feature is hot off the press — it was resolved on only two weeks ago — and currently only exists in spec text. The spec will most likely see some changes before this is ready for a browser to implement.

~

The Problem: Targeting Multiple Prefixed Classes

When coming up with classnames for use in the class attribute, a common practice is to use a prefix to retain some grouping or hierarchy. You might be familiar with classes like .btn-primary , .btn-secondary , .btn-danger , and so on.

To apply a base style to all of these buttons today, you typically have to list them all out, or introduce a separate .btn base class:

/* Adding a base class */ .btn { padding: 0.5rem 1rem; border-radius: 4px; } /* Or listing everything... yuck! */ .btn-primary, .btn-secondary, .btn-danger { padding: 0.5rem 1rem; border-radius: 4px; }

Some of you even resort to substring-matching attribute selectors, but those can be notoriously brittle and ugly when dealing with multiple classes on a single element:

/* Works, but can be error-prone with whitespace */ [class^="btn-"], [class*=" btn-"] { padding: 0.5rem 1rem; }

... continue reading