:last-child
:last-childは、親要素の最後の子要素を選択します。任意の要素タイプに適用できます。
使用例
/* 親要素の最後の子要素にスタイルを適用 */
.parent > :last-child {
background-color: #f0f0f0;
}
<div class="parent">
<p>最初の段落</p>
<p>最後の段落</p>
</div>
この例では、div.parentの最後の<p>要素に背景色が適用されます。
:last-of-type
:last-of-typeは、特定の要素タイプ内で最後の要素を選択します。これにより、同じタイプの要素の中で最後のものにスタイルを適用できます。
使用例
/* 親要素内の最後の<div>要素にスタイルを適用 */
.container div:last-of-type {
border: 2px solid #333;
}
<div class="container">
<div>最初のボックス</div>
<div>最後のボックス</div>
<span>スパン要素</span>
</div>
この例では、.container内の最後の<div>要素にボーダーが適用されますが、他の要素タイプ(例:<span>)には影響しません。
:last-childと:last-of-typeの違い
-
:last-child: 親要素の最後の子要素であれば、どのタイプでも選択されます -
:last-of-type: 親要素内で指定したタイプの最後の要素のみを選択します
比較例
/* :last-child */
.container > :last-child {
color: blue;
}
/* :last-of-type */
.container > :last-of-type {
color: red;
}
<div class="container">
<p>段落1</p>
<p>段落2</p>
<span>スパン</span>
</div>
-
:last-childは<span>スパン</span>を選択し、テキストが青色になります -
:last-of-typeは<p>段落2</p>要素に適用され、テキストが赤色になります