:first-of-type
在 CSS 虛擬類別(pseudo-class)中,
:first-of-type
代表本節點為兄弟節點中第一個此類型節點。
/* 選取第一個出現在父節點下的<p>,不考慮其在所有子節點中的位置。 */
p:first-of-type {
color: red;
}
附註: 在初始定義中,被選取的節點必須擁有父節點。從選取器層級4(Selectors Level 4)開始已經不再有這個限制了。
語法
:first-of-type
範例
例一:選取第一段文章
來考慮以下 HTML:
<h2>Heading</h2>
<p>Paragraph</p>
<p>Paragraph</p>
及 CSS:
p:first-of-type {
color: red;
}
會有這樣的效果 - 只有第一段文章變為紅色,因為它是 body 中第一個文章節點:
例二:預定通用選擇器(Assumed universal selector)
這個範例展示了當沒有指定一般選擇器(simple selector)時,通用選擇器是如何被預判。
首先來看 HTML:
<div>
<span>This `span` is first!</span>
<span>But this `span` isn't.</span>
<span>This <em>nested `em` is</em>!</span>
<span>And so is this <span>nested `span`</span>!</span>
<b>This `b` qualifies!</b>
<span>This final `span` does not.</span>
</div>
接著是 CSS:
div :first-of-type {
background-color: lime;
}
會有這樣的效果:
特定規格
規格 | 狀態 | 附註 |
---|---|---|
Selectors Level 4 The definition of ':first-of-type' in that specification. |
Working Draft | 配對節點不需要具有父節點。 |
Selectors Level 3 The definition of ':first-of-type' in that specification. |
Recommendation | 初始定義。 |
瀏覽器相容性
We're converting our compatibility data into a machine-readable JSON format.
This compatibility table still uses the old format,
because we haven't yet converted the data it contains.
Find out how you can help! (en-US)
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | 1.0 | (Yes) | 3.5 (1.9.1) | 9.0 | 9.5 | 3.2 |
Feature | Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | 2.1 | (Yes) | 1.0 (1.9.1) | 9.0 | 10.0 | 3.2 |