:first-of-type
试一试
语法
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;
}
结果
规范
规范 |
---|
选择器级别 4 # first-of-type-pseudo |
浏览器兼容性
BCD 表格仅在浏览器中加载