CSS セレクタとは
セレクタはルールの波かっこより前の部分です。宣言をどの要素に適用するかを決めます。
p.note { color: #2563eb; }
/* selector: p.note declaration: color: #2563eb */
実際のスタイルシートのほとんどは、次の 5 つの基本セレクタで書けます:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Basic selectors</title>
<style>
* { box-sizing: border-box; } /* universal: every element */
p { margin: 6px 0; } /* type: every <p> */
.tip { background: #e5e7eb; padding: 6px; } /* class */
#main-title { color: #2563eb; } /* ID: one element */
h2, .lead { font-style: italic; } /* group: either one */
</style>
</head>
<body>
<h1 id="main-title">Selectors</h1>
<p class="lead">A lead paragraph (grouped with h2).</p>
<p class="tip">A tip, matched by .tip</p>
<h2>A subheading</h2>
<p>A plain paragraph.</p>
</body>
</html>Master CSS the hands-on way
Interactive lessons, real projects, and instant feedback.
START NOW
セレクタの種類一覧
セレクタ 例 一致するもの 全称 *すべての要素 型 pすべての <p> クラス .tipclass="tip" を持つ要素 (他のクラスがあっても可)ID #main-titleid="main-title" を持つ要素属性 [type="email"]属性が一致する要素 疑似クラス a:hover, li:first-childある状態や位置にある要素 疑似要素 p::first-line, .x::before要素の一部分 グループ h1, h2, h3リストのいずれかに一致するもの 複合 p.tipそのクラスも持つ <p>
クラスと ID は CSS クラスセレクタ のページで、:nth-child() や :not() などの疑似クラスは 疑似クラスのページ で解説しています。
結合子: 子孫と子
結合子は、HTML ツリー内の関係によって 2 つのセレクタをつなぎます。全部で 4 つあります。
結合子 書き方 B が一致する条件子孫 A B (スペース)B が A の内側のどこかにある 子 A > BB の親が A 隣接兄弟 A + BB が A の直後にあり、親が同じ 一般兄弟 A ~ BB が A より後のどこかにあり、親が同じ
混同されやすいのはスペースと > です。子孫セレクタはどの深さにも届き、子セレクタは 1 階層で止まります:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Child selector</title>
<style>
li { padding: 2px 6px; margin: 2px 0; }
.all li { background: #e5e7eb; } /* descendant: every level */
.direct > li { border-inline-start: 4px solid #2563eb; } /* child: top level only */
</style>
</head>
<body>
<ul class="all direct">
<li>Top level: gray and blue edge</li>
<li>Top level: gray and blue edge
<ul>
<li>Nested: gray only</li>
<li>Nested: gray only</li>
</ul>
</li>
</ul>
</body>
</html>
兄弟結合子: + と ~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Siblings</title>
<style>
p { margin: 4px 0; padding: 4px 8px; }
h2 + p { background: #f59e0b; } /* only the first p after h2 */
h2 ~ p { color: #2563eb; } /* every p after h2 */
</style>
</head>
<body>
<p>Before the heading: untouched.</p>
<h2>Heading</h2>
<p>Right after h2: amber and blue.</p>
<p>Later sibling: blue only.</p>
<p>Later sibling: blue only.</p>
</body>
</html>
兄弟は前方しか見ません。「前の兄弟」を選ぶ結合子はありませんが、:has() で表現できます。h2:has(+ p) は直後に p が続く h2 に一致します。
属性セレクタ
角かっこで、属性とその値に基づいて一致させます:
セレクタ 一致するもの [disabled]その属性を持つ (値は何でもよい) [type="email"]値がちょうど email [href^="https"]値が https で始まる [href$=".pdf"]値が .pdf で終わる [class*="icon"]値のどこかに icon を含む [lang|="en"]値が en、または en- で始まる [data-state="open" i]大文字と小文字を区別しない完全一致
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Attribute selectors</title>
<style>
a { display: block; margin: 4px 0; }
a[href^="https"] { color: #16a34a; }
a[href$=".pdf"] { font-weight: bold; }
a[href$=".pdf"]::after { content: " (PDF)"; }
input[type="email"] { border: 2px solid #2563eb; }
[data-state="open"] { background: #e5e7eb; padding: 4px; }
</style>
</head>
<body>
<a href="https://example.com">External, https: green</a>
<a href="/guide.pdf">Guide, bold with a label</a>
<a href="/about">Relative link: untouched</a>
<input type="email" placeholder="Email: blue border">
<div data-state="open">data-state="open"</div>
</body>
</html>
data-* 属性に対する属性セレクタは、クラス名を考え出さずに、JavaScript が設定する状態をスタイルするきれいな方法です。
セレクタを試してみる
ボックスにセレクタを入力してください。一致したすべての要素にオレンジ色のアウトラインが付き、その下に件数が表示されます。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Selector tester</title>
<style>
.hit { outline: 3px solid #f59e0b; }
#demo { border: 1px solid #e5e7eb; padding: 8px; margin-top: 8px; }
#demo * { margin: 4px 0; }
</style>
</head>
<body>
<input id="sel" value="#demo li:nth-child(2)" size="30">
<span id="out"></span>
<div id="demo">
<h2 class="title">Title</h2>
<p class="intro">Intro <a href="/a">link</a></p>
<ul>
<li>One</li>
<li class="active">Two</li>
<li>Three <a href="https://example.com">external</a></li>
</ul>
</div>
<script>
const sel = document.getElementById('sel');
const out = document.getElementById('out');
const run = () => {
document.querySelectorAll('.hit').forEach((el) => el.classList.remove('hit'));
try {
const found = document.querySelectorAll(sel.value);
found.forEach((el) => el.classList.add('hit'));
out.textContent = found.length + ' match(es)';
} catch (e) {
out.textContent = 'Invalid selector';
}
};
sel.addEventListener('input', run);
run();
</script>
</body>
</html>
#demo a、ul > li、h2 ~ *、a[href^="https"]、li:not(.active) を試してみてください。
複合と子孫: スペースが意味を変える
p.note と p .note はスペース 1 つの違いですが、意味が異なります。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Space matters</title>
<style>
p.note { background: #e5e7eb; } /* a p that has .note */
p .note { color: #16a34a; font-weight: bold; } /* a .note inside a p */
</style>
</head>
<body>
<p class="note">p.note: gray background</p>
<p>Plain p with a <span class="note">span.note inside</span></p>
</body>
</html>
ブラウザのセレクタの読み方
複数のルールが同じ要素に一致し、同じプロパティを設定するときは、詳細度の高いセレクタが勝ち、同じなら後のルールが勝ちます。ID はクラスがいくつあっても上回り、クラスは型セレクタがいくつあっても上回ります。詳細度の表の全体は !important のページ にあります。
グループには 1 つ落とし穴があります。通常のリストのうち 1 つでも無効なセレクタがあると、ルール全体が捨てられます。a, b:unknown { } ではリンクさえスタイルされません。リストを :is() で囲むと寛容になり、:is(a, b:unknown) ならリンクはスタイルされます。
よくある間違い
ドットやハッシュを忘れる。 tip { } は class="tip" ではなく <tip> 要素を対象にします。.tip と書きましょう。
複合セレクタにスペースを入れる。 p .note は p.note ではありません。
> が孫要素にも届くと思う。 どの深さにも届かせるならスペースを使います。
1 つのタイプミスでグループ全体が壊れる。 h1, h2:hovr, h3 では何もスタイルされません。
長すぎるセレクタ。 body div.wrapper ul li a は読みにくく、上書きもしにくくなります。ほとんどの場合、クラス 1 つで十分です。