CSS 伪类 :first-of-type表示一组兄弟元素中其类型的第一个元素。

/* 选择在父元素中第一个出现的<p>,而不管其在兄弟内的位置如何 */
p:first-of-type {
  color: red;
}

Note:按原来定义,所选元素必须有一个父元素。 从 Selectors Level 4 开始,这不再需要。

语法

:first-of-type

例子

例1:选择第一个段落

我们看如下 HTML:

<h2>Heading</h2>

<p>Paragraph</p>

<p>Paragraph</p>

和这段 CSS:

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

这得到以下结果 — 只有第一个段落是红色,因为它是body内第一个出现的段落标签:

例2:假定通配选择器

这个例子展示了当没有写简单选择器时,通配选择器是如何被假定的。

首先,一些 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;
}

结果如下:

规范

Specification Status Comment
Selectors Level 4
:first-of-type
Working Draft Matching elements are not required to have a parent.
Selectors Level 3
:first-of-type
Recommendation Initial definition.

浏览器兼容

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
Basic supportChrome Full support 1Edge Full support YesFirefox Full support 3.5IE Full support 9Opera Full support 9.5Safari Full support 3.2WebView Android Full support 2Chrome Android ? Edge Mobile Full support YesFirefox Android Full support 4Opera Android Full support 10Safari iOS Full support 3.2Samsung Internet Android ?

Legend

Full support  
Full support
Compatibility unknown  
Compatibility unknown

相关知识

文档标签和贡献者

此页面的贡献者: Ritr, zhangchen, xgqfrms-GitHub, ZackBee, sgzzy, Orange-C, sudo2015
最后编辑者: Ritr,