CSSを適用する要素を絞り込む階層指定
CSSのセレクタは次の4種類の結合子を使って階層指定を行うことができます。
階層形式 | 名前 |
---|---|
セレクタA セレクタB | 子孫結合子 |
セレクタA > セレクタB | 子結合子 |
セレクタA + セレクタB | 隣接兄弟結合子 |
セレクタA ~ セレクタB | 一般兄弟結合子 |
今回はこれらのセレクタの階層指定について、コードを交えながら解説していきます。
子孫結合子
セレクタを半角スペースで繋ぐ結合子で、かなり頻繁に使う階層指定です。
要素の親子関係をそのまま記述する形のため、直感的に理解もしやすく扱いやすい指定方法です。
style.css
section p {
margin-bottom: 15px;
}
section div p {
font-weight: bold;
color: green;
}
index.html
<section>
<p>テキスト1</p>
<div>
<p>テキスト2</p>
</div>
<p>テキスト3</p>
</section>

子結合子
セレクタを「>(右アングルブラケット)」で繋げる階層指定です。
次のようなHTMLの場合、section要素の直接の子孫となるp要素にのみスタイルを適用します。
そのため、section要素の子孫要素にあたる「テキスト2」のテキストを持つp要素は直接の親要素がdiv要素になるためスタイルが適用されません。
style.css
section p {
margin-bottom: 15px;
}
section > p {
font-weight: bold;
color: blue;
}
index.html
<section>
<p>テキスト1</p>
<div>
<p>テキスト2</p>
</div>
<p>テキスト3</p>
</section>
div要素内のp要素にはfont-weightプロパティとcolorプロパティが適用されません。

隣接兄弟結合子
セレクタを「+(プラス)」で繋げる階層指定です。
次のようなHTMLの場合、h1要素に隣接するp要素にのみスタイルを適用します。
style.css
section p {
margin-bottom: 15px;
}
h1 + p {
font-weight: bold;
color: blue;
}
index.html
<section>
<h1>見出し</h1>
<p>テキスト1</p>
<p>テキスト2</p>
<p>テキスト3</p>
</section>

一般兄弟結合子
セレクタを「~(チルダ)」で繋げる階層指定です。
「h1 ~ p」のように記述し、左側にある要素より後にあり、かつ同じ階層(同じ親要素を持つ)の要素にスタイルを適用することができます。
次のようなHTMLの場合、h1要素と同階層にあるp要素のうち、後ろにある「テキスト2」と「テキスト4」というテキストが入ったp要素の2つのみスタイルを適用します。
「テキスト1」のp要素はh1要素よりも前にあるためスタイルが適用されません。
もう1つの「テキスト3」が入ったp要素は同じ階層でないため、こちらもスタイルが適用されません。
style.css
section p {
margin-bottom: 15px;
}
h1 ~ p {
font-weight: bold;
color: #c00;
}
index.html
<section>
<p>テキスト1</p>
<h1>見出し</h1>
<p>テキスト2</p>
<div>
<p>テキスト3</p>
</div>
<p>テキスト4</p>
</section>

複数の結合子を組み合わせて階層指定を絞り込む
ここまで紹介した4種類の結合子は組み合わせて階層指定することもできます。
次の例では「子孫結合子」「一般兄弟結合子」「子結合子」の3種類の結合子を使って、「テキスト3」のテキストを持つp要素にスタイルを適用します。
style.css
section p {
margin-bottom: 15px;
}
section h1 ~ div > p {
color: #00f;
}
index.html
<section>
<p>テキスト1</p>
<h1>見出し</h1>
<p>テキスト2</p>
<div>
<p>テキスト3</p>
</div>
<p>テキスト4</p>
</section>
