:first-of-type

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

:first-of-type CSS 偽類表示在一組兄弟元素中,特定型別(標籤名)的第一個元素。

試一試

dt {
  font-weight: bold;
}

dd {
  margin: 3px;
}

dd:first-of-type {
  border: 2px solid orange;
}
<dl>
  <dt>Vegetables:</dt>
  <dd>1. Tomatoes</dd>
  <dd>2. Cucumbers</dd>
  <dd>3. Mushrooms</dd>
  <dt>Fruits:</dt>
  <dd>4. Apples</dd>
  <dd>5. Mangos</dd>
  <dd>6. Pears</dd>
  <dd>7. Oranges</dd>
</dl>

語法

css
:first-of-type {
  /* ... */
}

示例

設定第一個段落的樣式

HTML

html
<h2>Heading</h2>
<p>Paragraph 1</p>
<p>Paragraph 2</p>

CSS

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

結果

巢狀元素

此示例展示瞭如何定位巢狀元素。請注意,當未編寫型別選擇器時,將隱式使用通用選擇器*)。

HTML

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>
  <p>This `p` qualifies!</p>
  <div>This is the final `div`.</div>
</article>

CSS

css
article :first-of-type {
  background-color: pink;
}

結果

規範

規範
選擇器 Level 4
# first-of-type-偽類

瀏覽器相容性

另見