セレクタは、ルールが適用される要素を特定します。シンプルなもの(タグによるもの)から強力なコンビネータまで様々です。
css
/* Basic selectors */
p { } /* type: all <p> */
.card { } /* class: elements with class="card" (reusable) */
#header { }
* { }
{ }
.menu li { } /* descendant: any li INSIDE .menu (any depth) */
.menu > li { } /* child: only DIRECT children li */
h2 + p { } /* adjacent sibling: the p immediately AFTER an h2 */
h2 ~ p { } /* general sibling: all p siblings after an h2 */
空白(子孫)と>(直接の子)の違いは重要です:.menu liは深くネストされたliにもマッチしますが、.menu > liはトップレベルのみにマッチします。
a:hover { } /* state: while hovered */
li:first-child { } /* structural: the first li */
li:nth-child(2n){ } /* every even li */
p::first-line { } /* pseudo-element: the first rendered line */
h1, h2, h3 { } /* apply to all three */
:is(h1, h2) a { } /* :is() shortens long selector lists */
.card:has(img) { } /* :has() — a parent that CONTAINS an img */
セレクタは、スタイルをマークアップに接続する方法です。
クラス(主要なツール)、コンビネータ(関係性用)、構造的/状態疑似クラスをマスターすることで、あちこちに余分なクラスを追加せずに正確にターゲットできます — そして、モダンな:is()/:has()は複雑なターゲティングを簡潔にします。
id/深いネストより、クラスを優先して特異性を管理可能に保ちましょう。
ジュニアからシニアまで、詳細な回答付きのIT面接質問ライブラリ。
寄付する