hasとは引数の中で指定した条件(少なくとも1つ以上)を含んでいる要素をチェックできる擬似クラスです。実際にどういう場面で利用できるのか気になったので調べました。
例えば、直下にdiv要素を持つdl要素の場合、以下のようになります↓
<style>
dl:has(> div) {
/*style*/
}
</style>
<dl>
<div>
<dt>...</dt>
<dd>...</dd>
</div>
</dl>
目次
使用例
ul要素内でhoverされていない全てのa要素を選択
See the Pen Untitled by ユイト (@mikiprogram) on CodePen.
こちらの動きは、ul:hover a:not(:hover){}
と指定しても可能です。hasを使わなくてもできます。
項目「その他」を選んだときに現れる入力エリア
Ahmad ShadeedさんのCodepenから引用↓
See the Pen CSS :has – Other field by Ahmad Shadeed (@shadeed) on CodePen.
イライラ棒
web.devさんのCodePenから引用↓
See the Pen Do you :has a steady hand? 👋 [Pure CSS Game] by web.dev (@web-dot-dev) on CodePen.
私はどうなっているのか全く分かっていません。
その他の例
他の使用例は、以下の記事から確認してください↓
Chrome for Developers
:has(): the family selector | Blog | Chrome for Developers
With :has() landing in Chromium 105. Let's take a look at some of the awesome opportunities it brings to our CSS!
LogRocket Blog


The advanced guide to the CSS :has() selector – LogRocket Blog
The :has() pseudo-class has been a much-awaited addition to CSS – discover advanced implementations in this complete guide.
あわせて読みたい


Conditional CSS with :has and :nth-last-child
A modern look at how to combine CSS :has, :nth-last-child, and style queries to create dynamic components.
実際のサイトでの使用例
実際のサイトでは、どんな場面で使用されているか気になり調べてみました。
【公式】一棟貸しの絶景ヴィラ|十八楼 離れ「宿いとう」|岐阜
十八楼 離れ 宿いとう


十八楼 離れ 宿いとう
岐阜市にある一棟貸し切りの絶景ヴィラ「十八楼 離れ 宿いとう」の公式サイトです。かつて皇族もご宿泊した歴史ある旅館をモダンにリノベーション。鵜飼で有名な長良川沿い…
/*該当コード一部*/
.btn a:has(.icon-pdf) {
padding-left: 56px;
}
Neko Health
あわせて読みたい
Neko Health
Try the Neko Body Scan. Get answers right away, and let us monitor your health – so you don’t have to.
/*該当コード*/
[data-ui=PaneItem] [data-testid=Media]:has(img) {
display: none
}
Future Explorations | 100BANCH
Future Explorations | 100BANCH


Future Explorations | 100BANCH
Future Explorationsは、100BANCHに集う若者たちによる300以上のプロジェクトから見えてきた未来の兆しを、より深く、より遠くへ広げていく未来社会のResearch & Design活…
/*該当コード*/
[class*=Futures_futures]:has([class*=IndexItem_link]:hover) .CloseUpCursor_closeUpCursor__zZ3Su {
opacity: 1;
-webkit-transform: scale(1);
transform: scale(1)
}
ブラウザ対応状況
記事執筆時点(2023/07/11)では、Firefox以外の主要なブラウザは対応しています。
まとめ
現状ではFirefoxが未対応で、Safariも15.4から対応なので実案件に使用するのは先になりそうです。
私はhasを使わないといけない例が思いつかず、「それって無理やりhas使ってるやん!」という例しか思いつきませんでした。
もっと使用例ググって勉強します。
参考
あわせて読みたい
関係擬似クラス :has() でホバーしている要素の前の隣接要素を指定する – dskd
10年前の夢を追って
WebKit
Using :has() as a CSS Parent Selector and much more
It’s been a long-standing dream of front-end developers to have a way to apply CSS to an element based on what’s happening inside that element.