こんにちは、さち です。
先日、CSS を書いているときに :has() を「入れ子(ネスト)」を使いたいことがありました。
しかし、:has() は「入れ子」に対応していません。
ただ、できないわけではありません。セレクターの書き方を工夫すれば :has() の「入れ子」と同じ効果を得ることができます。
実装方法
サンプルソース
<div class="one">
<div class="two">
<div class="three">
</div>
</div>
</div>
<div class="one">
<div class="two">
</div>
</div>
<div class="one">
<div class="three">
</div>
</div>
.three を「子孫」として持つ .two があり、さらにその .two を「子孫」として持つ .one を選択する CSS セレクターを書いてみます。
.one, .two, .three {
background: white;
border-color: dimgray;
}
/* :has() の入れ子【動かない】 */
.one:has(.two:has(.three)) {
border-color: red;
}
/* 入れ子を回避した書き方【動く】 */
.one:has(.two .three) {
background: lightgreen;
}
直訳して CSS セレクターに落とし込むと .one:has(.two:has(.three)) になりますが、:has() の「入れ子」になっているので動作しません。
そこで、.two:has(.three) を別の書き方にしましょう。.three は .two の「子孫」だと表せれば十分なので、.two .three に変換できますね。
つまり、 .one:has(.two:has(.three)) は .one:has(.two .three) に書き換えできるわけです。これで :has() の「入れ子」を解消できました。
結果
表示結果
.one:has(.two:has(.three)) で指定した border-color: red; は機能していません。( :has() の「入れ子」は使えないため)
.one:has(.two .three) で指定した background: lightgreen; は機能しています。また、.two または .three だけを「子孫」に持つ .one には適用されていません。
思い通りの動作をする CSS を実装できました。

コメント