首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

:first-of-type

该:first-of-typeCSS伪类表示其同类型的一组同胞元素中的第一个元素。

代码语言:javascript
复制
/* Selects the first <p> to appear inside a parent element
   regardless of its position inside the siblings */
p:first-of-type {
  color: red;
}

注意:如最初定义的那样,所选元素必须有一个父元素。但是从选择器级别4开始,这不再是必需的。

语法

代码语言:javascript
复制
:first-of-type

实例

例1:简单地选择第一个段落

我们来考虑下面的HTML:

代码语言:javascript
复制
<h2>Heading</h2>

<p>Paragraph</p>

<p>Paragraph</p>

和下列CSS:

代码语言:javascript
复制
p:first-of-type {
  color: red;
}

这就给出了以下结果--仅有第一段为红色,因为它是第一个出现在正文中的段落类型元素:

示例2:假定的通用选择器

此示例演示了在没有编写简单选择器时如何假定通用选择器。

首先,一些HTML如下:

代码语言:javascript
复制
<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:

代码语言:javascript
复制
div :first-of-type {
  background-color: lime;
}

结果如下:

规范

Specification

Status

Comment

Selectors Level 4The definition of ':first-of-type' in that specification.

Working Draft

Matching elements are not required to have a parent.

Selectors Level 3The definition of ':first-of-type' in that specification.

Recommendation

Initial definition.

浏览器兼容性

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

扫码关注腾讯云开发者

领取腾讯云代金券