:first-child
は CSS の擬似クラスで、兄弟要素のグループの中で最初の要素を表します。
/* 兄弟要素の中で最初の <p> を
すべてを選択 */
p:first-child {
color: lime;
}
注: 最初の定義では、親のある要素のみが選択されていました。 Selectors Level 4 の初期に、これは必要なくなりました。
構文
:first-child
例
基本的な例
HTML
<div>
<p>This text is selected!</p>
<p>This text isn't selected.</p>
</div>
<div>
<h2>This text isn't selected: it's not a `p`.</h2>
<p>This text isn't selected.</p>
</div>
CSS
p:first-child {
color: lime;
background-color: black;
padding: 5px;
}
結果
リストのスタイル付け
HTML
<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>
CSS
ul li {
color: blue;
}
ul li:first-child {
color: red;
font-weight: bold;
}
結果
仕様書
仕様書 | 状態 | 備考 |
---|---|---|
Selectors Level 4 :first-child の定義 |
草案 | 選択する要素に親を必要としないようにした。 |
Selectors Level 3 :first-child の定義 |
勧告 | 変更なし。 |
CSS Level 2 (Revision 1) :first-child の定義 |
勧告 | 初回定義 |
ブラウザーの互換性
BCD tables only load in the browser