The CSS :has() selector is way more than a “Parent Selector”
Safari Technology Preview 137 just dropped, with unflagged support for CSS :has()
. Often dubbed “the parent selector”, CSS :has()
is way more than that …
~
# CSS :has()
?
As per selectors-4 specification:
The
:has()
CSS pseudo-class represents an element if any of the selectors passed as parameters match at least one element.
This selector is dubbed “the parent selector”, as the default cases indeed allow you to select a parent element that has certain children.
/* Matches only <a> elements that directly contain an <img> child */
a:has(> img) { … }
/* Matches <h1> elements only if they have a <p> element directly following them */
h1:has(+ p) { … }
/* Matches <section> elements that don’t contain any heading elements: */
section:not(:has(h1, h2, h3, h4, h5, h6))
Cool!
~
# More than a parent selector
The :has()
selector is way more than that just a parent selector though. As Adrian Bece shared in his post on Smashing Magazine:
/* Matches <figure> elements that have a <figcaption> as a child element */
figure:has(figcaption) { … }
/* Matches <img> elments that is a child of a <figure> that contains a <figcaption> child element */
figure:has(figcaption) img { … }
Here’s a pen:
See the Pen The CSS :has() selector is way more than a “Parent Selector” by Bramus (@bramus)on CodePen.
In browsers that support :has()
you should see a red dashed border around the top image.
~
# Browser Support
As mentioned only Safari TP 137 supports it (unflagged) at the time of writing. Chromium is currently also working on implementing it. No word on Firefox.
- WebKit/Safari: Issue #227702 — RESOLVED FIXED
- Blink/Chromium: Issue #669058 — Assigned (Open)
- Gecko/Firefox: Issue #418039 — NEW
Interative Support Chart (using data from CanIUse.com):
Data on support for the mdn-css__selectors__has feature across the major browsers
The pen embedded below will indicate if your browser supports CSS :has()
or not:
See the Pen
CSS :has Selector Support test by Bramus (@bramus)
on CodePen.
~
🔥 Like what you see? Want to stay in the loop? Here's how: