:first-of-type
CSS の :first-of-type
疑似クラスは、兄弟要素のグループの中でその種類の最初の要素を表します。
/* 兄弟要素の中で最初の <p> 要素をすべて選択 */
p:first-of-type {
color: red;
}
メモ: 当初の定義では、親のある要素のみが選択されていました。 Selectors Level 4 の初期に、これは必要なくなりました。
構文
:first-of-type
例
最初の段落の整形
HTML
<h2>Heading</h2>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
CSS
p:first-of-type {
color: red;
font-style: italic;
}
結果
ネストした要素
この例は、どうやった入れ子になった要素を対象にするかを示します。なお、単純セレクターが書かれていない場合は、ユニバーサルセレクター (*
) が暗黙に含まれています。
HTML
<article>
<div>This `div` is first!</div>
<div>This <span>nested `span` is first</span>!</div>
<div>This <em>nested `em` is first</em>, but this <em>nested `em` is last</em>!</div>
<div>This <span>nested `span` gets styled</span>!</div>
<b>This `b` qualifies!</b>
<div>This is the final `div`.</div>
</article>
CSS
article :first-of-type {
background-color: pink;
}
結果
仕様書
仕様書 | 策定状況 | コメント |
---|---|---|
Selectors Level 4 :first-of-type の定義 |
草案 | 選択する要素に親を必要としないようにした。 |
Selectors Level 3 :first-of-type の定義 |
勧告 | 初回定義。 |
ブラウザー実装状況
BCD tables only load in the browser