--- title: ':last-child' slug: 'Web/CSS/:last-child' tags: - CSS - Layout - Pseudo-class - Reference - Selector - Web translation_of: 'Web/CSS/:last-child' ---
:last-child はCSS の擬似クラスで、兄弟要素のグループの中で最後の要素を表します。
/* 兄弟要素の中で最後の <p> を
すべてを選択 */
p:last-child {
color: lime;
}
注: 当初の定義では、親のある要素のみが選択されていました。 Selectors Level 4 の初期に、これは必要なくなりました。
<div> <p>This text isn't selected.</p> <p>This text is selected!</p> </div> <div> <p>This text isn't selected.</p> <h2>This text isn't selected: it's not a `p`.</h2> </div>
p:last-child {
color: lime;
background-color: black;
padding: 5px;
}
{{EmbedLiveSample('Basic_example', 500, 200)}}
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3
<ul>
<li>Item 3.1</li>
<li>Item 3.2</li>
<li>Item 3.3</li>
</ul>
</li>
</ul>
ul li {
color: blue;
}
ul li:last-child {
border: 1px solid red;
color: red;
}
{{EmbedLiveSample('Styling_a_list')}}
| 仕様書 | 状態 | 備考 |
|---|---|---|
| {{SpecName('CSS4 Selectors', '#the-last-child-pseudo', ':last-child')}} | {{Spec2('CSS4 Selectors')}} | 選択する要素に親を必要としないようにした。 |
| {{SpecName('CSS3 Selectors', '#last-child-pseudo', ':last-child')}} | {{Spec2('CSS3 Selectors')}} | 初回定義 |
{{Compat("css.selectors.last-child")}}