:is() / :not() / :has() を組み合わせた「クラスベースの位置選択」までを整理しました。それぞれのセレクタでどの要素が赤くなるかを、実際に表示して確認できます。

nth-系セレクタの実例まとめ|:nth-of-type() の基本から、:nth-child の of構文 まで | CODE PLUS(コードプラス) nth-系セレクタの実例まとめ|:nth-of-type() の基本から、:nth-child の of構文 まで | CODE PLUS(コードプラス) 「最初の要素だけスタイルを変えたい」「最後の3つだけマージンをなくしたい」——こういった位置ベースの指定はCSSでよく書く書き方です。:nth-of-type() の基本から、:nth-child の of 構文までを整理しました。それぞれのセレク...  続きを読む

1. 自分自身のクラス

全ての li に .target が付き、③ ⑤ ⑥ ⑧ にはさらに .christina が付いています。

.christina を持つ

li.christina { background: red; }

.christina を持たない

li:not(.christina) { background: red; }

2. 子孫・直下の子(:is / :not)

入れ子の div.target で関係を見ます。③ が .christina で、④ と ⑥ が直下の子、⑤ は孫です。

.christina の子孫要素

.christina .target,
.target:is(.christina *) { background: red; }

.christina の子孫要素ではない

.target:not(.christina *) { background: red; }

.christina の直下の子要素

.christina>.target,
.target:is(.christina>*) { background: red; }

.christina の直下の子要素ではない

.target:not(.christina>*) { background: red; }

.christina を持つ、もしくは直下の子要素

.target:is(.christina, .christina>*) { background: red; }

.christina を持たず、直下の子要素でもない

.target:not(.christina, .christina>*) { background: red; }

3. 祖先・親(:has)

.christina の祖先要素(子孫要素に .christina がある)

.target:has(.christina) { background: red; }

.christina の親要素(直下の子要素に .christina がある)

.target:has(>.christina) { background: red; }

4. .christina を持つ要素の中での位置

① 〜 ⑨ のうち ③ ⑤ ⑥ ⑧ が .christina です。

.christina の最初の要素

.christina:not(.christina~*) { background: red; }

.christina の最初以外

.christina:is(.christina~*) { background: red; }

.christina の最後の要素

.christina:not(:has(~.christina)) { background: red; }

.christina の最後以外

.christina:has(~.christina) { background: red; }

5. 隣接・兄弟関係

.target は全ての li に付いているため、.christina 自身も対象になり得る点に注意してください(⑤ の直後の ⑥ も .christina です)。

.christina の直後の要素

.christina+.target { background: red; }

.christina の後ろすべての要素

.christina~.target { background: red; }

.christina の直後の要素ではない

.target:not(.christina+*) { background: red; }

.christina の直前の要素

.target:has(+.christina) { background: red; }

.christina より前のすべての要素

.target:has(~.christina) { background: red; }

関連記事

nth-系セレクタの実例まとめ|:nth-of-type() の基本から、:nth-child の of構文 まで | CODE PLUS(コードプラス) nth-系セレクタの実例まとめ|:nth-of-type() の基本から、:nth-child の of構文 まで | CODE PLUS(コードプラス) 「最初の要素だけスタイルを変えたい」「最後の3つだけマージンをなくしたい」——こういった位置ベースの指定はCSSでよく書く書き方です。:nth-of-type() の基本から、:nth-child の of 構文までを整理しました。それぞれのセレク...  続きを読む