うも、くまだです。
わりと最近使えるようになったCSSの疑似クラス:where()と:is()についてのあれこれ。
LPデザインのお仕事募集中です↓↓↓
疑似クラス:where()
:where()は複数のセレクタを1つにまとめて書くことができます。
例えば、普通にCSSを書くと、
<div class="box">
<p class="text">テキスト</p>
</div>
<div class="box2">
<p class="text">テキスト</p>
</div>
<div class="test">
<p class="text">テキスト</p>
</div>
.box p, .box2 p,.test p{
color: red;
}
![](https://sp-ao.shortpixel.ai/client/to_webp,q_glossy,ret_img,w_488,h_219/https://weblife.ppmp556.com/wp-content/uploads/2024/03/356e5928-c0a9-457f-948c-5cf46a4af82d.png)
これを:where()を使うと、下みたいにひとまとめで書けます。
:where(.box, .box2, .test) .text{
color: red;
}
![](https://sp-ao.shortpixel.ai/client/to_webp,q_glossy,ret_img,w_488,h_219/https://weblife.ppmp556.com/wp-content/uploads/2024/03/356e5928-c0a9-457f-948c-5cf46a4af82d.png)
:where()の特徴として詳細度を持たないので、下のように指定すればスタイルを上書きできます。
:where(.box, .box2, .test) .text{
color: red;
}
.text {
color: blue;
}
![](https://sp-ao.shortpixel.ai/client/to_webp,q_glossy,ret_img,w_393,h_202/https://weblife.ppmp556.com/wp-content/uploads/2024/03/e3e7e571-314e-4dee-8799-61cd676292b9.png)
疑似クラス:is()
:is()も、:where()と同様にひとまとめに書くことができます。
:is(.box, .box2, .test) .text{
color: red;
}
![](https://sp-ao.shortpixel.ai/client/to_webp,q_glossy,ret_img,w_488,h_219/https://weblife.ppmp556.com/wp-content/uploads/2024/03/356e5928-c0a9-457f-948c-5cf46a4af82d.png)
:where()との違いは:where()は詳細度が0なのに対し、is()は引数内で最も詳細度の高いセレクタの詳細度になります。
以下のように指定した場合、テキストの色は青になりません。
:is(.box, .box2, .test) .text{
color: red;
}
.text {
color: blue; /* こちらは効かない */
}
:where()のほうが使いやすそうなイメージです。
ここまで読んでくださりありがとうございました。