:first-of-type

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

在 CSS 虛擬類別(pseudo-class)中,:first-of-type 代表本節點為兄弟節點中第一個此類型節點。

css
/* 選取第一個出現在父節點下的<p>,不考慮其在所有子節點中的位置。 */
p:first-of-type {
  color: red;
}

備註: 在初始定義中,被選取的節點必須擁有父節點。從選取器層級 4(Selectors Level 4)開始已經不再有這個限制了。

語法

Error: could not find syntax for this item

範例

例一:選取第一段文章

來考慮以下 HTML:

html
<h2>Heading</h2>

<p>Paragraph</p>

<p>Paragraph</p>

及 CSS:

css
p:first-of-type {
  color: red;
}

會有這樣的效果 - 只有第一段文章變為紅色,因為它是 body 中第一個文章節點:

例二:預定通用選擇器(Assumed universal selector)

這個範例展示了當沒有指定一般選擇器(simple selector)時,通用選擇器是如何被預判。

首先來看 HTML:

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:

css
div :first-of-type {
  background-color: lime;
}

會有這樣的效果:

特定規格

Specification
Selectors Level 4
# first-of-type-pseudo

瀏覽器相容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
:first-of-type

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
See implementation notes.

參見