:first-of-type
:first-of-type
该:first-of-type
CSS伪类表示其同类型的一组同胞元素中的第一个元素。
/* Selects the first <p> to appear inside a parent element
regardless of its position inside the siblings */
p:first-of-type {
color: red;
}
注意
:如最初定义的那样,所选元素必须有一个父元素。但是从选择器级别4开始,这不再是必需的。
语法
:first-of-type
实例
例1:简单地选择第一个段落
我们来考虑下面的HTML:
<h2>Heading</h2>
<p>Paragraph</p>
<p>Paragraph</p>
和下列CSS:
p:first-of-type {
color: red;
}
这就给出了以下结果--仅有第一段为红色,因为它是第一个出现在正文中的段落类型元素:
示例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 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 |