セレクタ同士を適切に組み合わると、効率よく効果的に装飾することができます。この場合、要素同士がどんな関係にあるかを把握する必要があります。
セレクタとセレクタとの間に在ってセレクタ同士をつなぐ役割を担う記号を結合子、コンビネータと呼びます。
コンビネータ
装飾の指定はHTMLの構造に基づきます。
<section class="combinator"> /*親要素
<h2>combinators</h2> /*子要素
<p>selector list> /*子要素
<div> /*子要素
<p>Child</p> /*子孫要素=>孫要素
<p>Descendant</p> /*孫要素
<p>Next-sibling</p> /*孫要素
<p>Subsequent-sibling</p> /*孫要素
</div>
</section>
セレクタリスト
,
同じ装飾を施したい要素を並べて指定します。繋いだ要素全てに同じ装飾が施されます。
h2,div,p {
color: red;
}
combinators
selector list
Child
Descendant
Next-sibling
Subsequent-sibling
子結合子
>
親要素の直接の子要素にだけ、装飾を施します。子孫要素であるdiv.combinator以下の孫要素のp要素には適用されません。
section.combinator > p {
color: red;
}
combinators
selector list
Child
Descendant
Next-sibling
Subsequent-sibling
子孫結合子
(半角スペース)
子孫要素全てに装飾を施します。
section.combinator p {
color: red;
}
combinators
selector list
Child
Descendant
Next-sibling
Subsequent-sibling
次兄弟結合子
+
同じ親を持つ子要素の次の要素に装飾を施します。本人に飾りつけは施されません。
<div> /*親要素
<p class="first">Child</p> /*子要素
<p>Descendant</p> /*子要素
<p>Next-sibling</p> /*子要素
<p>Subsequent-sibling</p> /*子要素
</div>
p.first + p {
color: red;
}
Child
Descendant
Next-sibling
Subsequent-sibling
後続兄弟結合子
~
同じ親を持つ子要素(本人を除いて全て)に装飾を施します。
<section> /*親要素
<h2 class="combinators">Combinators</h2> /*子要素
<p>Child</p> /*子要素
<p>Descendant</p> /*子要素
<p>Next-sibling</p> /*子要素
<p>Subsequent-sibling</p> /*子要素
</section>
h2.combinators ~ p {
color: red;
}
Combinators
Child
Descendant
Next-sibling
Subsequent-sibling