[CSS] 疑似クラス is() とwhere() の使い方と違い
CSSの比較的新しい疑似クラス :is() と :where() の使い方と違いについてまとめました。
:is()
:is() の括弧内に複数のセレクタをカンマ区切りで指定すると、異なるセレクタにまとめて同じスタイルを適用できます。
1 2 3 4 5 6 7 8 9 10 11 |
/* 従来の書き方 */ .cols_2 div , .cols_2 li , .cols_2 article { width: calc(100% / 2 - 40px / 2); } /* :is() を使った書き方 */ .cols_2 > :is(div, li, article) { width: calc(100% / 2 - 40px / 2); } |
:where()
:where() の構文と機能は、 :is() と同じです。
1 2 3 |
:where(div, li, article) { width: calc(100% / 2 - 40px / 2); } |
では、両者はどこが違うのでしょうか?
:is() と :where() の違い
:is() と :where() の違いは、セレクタの詳細度(優先度)にあります。
言葉では分かりにくいので、以下のサンプルを見てみましょう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<div class="container is-example"> <p class="sample1"><a href="#">sample1</a></p> <p class="sample2"><a href="#">sample2</a></p> <p class="sample3"><a href="#">sample3</a></p> </div> <div class="container where-example"> <p class="sample1"><a href="#">sample1</a></p> <p class="sample2"><a href="#">sample2</a></p> <p class="sample3"><a href="#">sample3</a></p> </div> <pre class="theme:arduino-ide lang:default decode:true " > /* :is() の例 */ .is-example :is(.sample1, .sample2, .sample3) a { color: red; } /* :where() の例 */ .where-example :where(.sample1, .sample2, .sample3) a { color: blue; } /* 比較用 */ .sample1 a { color: green; } |
実行結果
→ where の .sample1 だけが緑色に上書きされました。
上記のコードから、sample1に関わる部分だけを抜き出すと次のようになります。
1 2 3 4 5 6 7 8 9 10 11 |
.is-example :is(.sample1) a { color: red; } .where-example :where(.sample1) a { color: blue; } .sample1 a { color: green; } |
・:is() は、セレクタ全体の詳細度に影響します。
.is-example :is(.sample1) a はクラスセレクタを2つ以上含むため、.sample1 a よりも詳細度が高く、赤色が優先されます。
・:where() は、括弧内のセレクタが何であっても、詳細度は常に0 になります。
そのため、.where-example :where(.sample1) a よりも .sample1 a が優先され、緑色が適用されます。
セレクタの詳細度についてさらに学びたい方はこちらの記事もチェックしてみてください。