Using the :has() Selector for Proactive Component Styling

Learn how to use :has() in CSS for dynamic styling of components, such as buttons, based on element presence, enabling enhanced design flexibility.

Now that we understand the essential mechanics of using :has() , we’re going to use it to style some practical components. With :has(), we can provide proactive stying instead of relying on the application of classes.

At the time of writing, the demos that follow will only work in Safari 15.4+ or Chrome/Edge 105+ or with the layout.css.has-selector.enabled flag enabled in Firefox 103+. Please refer here for the most up-to-date support information.

Button layouts using :has() and :not()

The combination of :has() with :not() is a powerful pairing of selectors.

Consider variants of a button component, such as text-only, text plus an icon, and icon-only. Depending on the presence of an SVG icon and whether or not the button text is visible, the base <button> element should receive slightly different properties.

For reference, here’s the HTML with the full SVG string omitted:

Get hands-on with 1400+ tech skills courses.