Photo by Maik Jonietz on Unsplash

The CSS :has() selector

The :has() CSS pseudo-class represents an element if any of the selectors passed as parameters match at least one element.

In earlier revisions of the CSS Selectors Level 4 specification, :has had a limitation that it couldn't be used within stylesheets. Instead, it could only be used with functions like document.querySelector(); this was due to performance concerns. This limitation has been removed because no browser implemented it that way. Instead, browsers currently only support the use of :has() within stylesheets.

For example, the following selector matches only <a> elements that contain an <img> child:

When selector matches a <dt> element immediately followed by another <dt> element:

When selector matches <section> elements that don't contain any heading elements:

Or swapping the nesting of the two pseudo-classes:

Safari Technology Preview Release 137 is now available for download and enabled support for :has() pseudo-class by default. The Chromium is not supported right now, but they currently working on implementing it. Firefox is not supported right now.

Originally published at https://ronaldsvilcins.com on December 22, 2021.

--

--

I drink a lot of tea and build beautiful websites. If you are looking to work together or just start a conversation 👉 https://www.ronaldsvilcins.com/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ronalds Vilcins

I drink a lot of tea and build beautiful websites. If you are looking to work together or just start a conversation 👉 https://www.ronaldsvilcins.com/