1211 1939 1626 1765 1058 1212 1711 1446 1364 1191 1734 1179 1503 1068 1462 1943 1307 1349 1696 1248 1687 1043 1451 1188 1388 1751 1008 1404 1328 1032 1040 1389 1799 1882 1437 1876 1351 1621 1096 1515 1999 1519 1238 1915 1328 1628 1403 1635 1997 1301 1722 1266 1489 1778 1975 1302 1567 1920 1955 1967 1820 1178 1162 1647 1863 1654 1596 1862 1884 1582 1819 1419 1245 1801 1121 1423 1634 1245 1709 1831 1896 1586 1614 1501 1592 1020 1526 1764 1581 1400 1496 1598 1182 1992 1598 1181 1628 1508 1976 The CSS :has() selector is way more than a “Parent Selector” | PHPnews.io

PHPnews.io

The CSS :has() selector is way more than a “Parent Selector”

Written by Bram.us / Original link on Dec. 21, 2021

styles.css.png

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.

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:

bram tutorialzine selectors bram

« Deep-copying in JavaScript using structuredClone - Easing Gradients »