CSS 伪类选择器 :first-of-type 用于在其父容器中选择其类型的第一个元素并设置其样式。通过此伪类,您可以专门针对给定容器中某种元素的第一次出现来定位和应用样式。
CSS 伪类选择器 :first-child 类似于 :first-of-type,但有一个区别:它不那么具体。:first-child 仅匹配父元素的第一个子元素;而 :first-of-type 匹配指定元素的子元素,即使它不是第一个。
语法
:first-of-type {
/* ... */
}
CSS :first-of-type 示例
以下示例演示了在 <div> 父元素下的 <p> 标记上使用 :first-of-type 伪类。
在此示例中,CSS 规则仅适用于在 <div> 元素中找到的第一个 <p> 元素,而同一容器中的其他 <p> 元素不受影响。
<html>
<head>
<style>
p:first-of-type {
color: black;
background: peachpuff;
font-weight: 600;
font-size: 1em;
font-style: italic;
padding: 5px;
}
div {
border: 2px solid black;
margin-bottom: 5px;
}
</style>
</head>
<body>
<div>Parent element
<p>first child looks different due to :first-of-type pseudo-class</p>
<p>second child, so no change</p>
</div>
<div>Parent element
<h3>h3 tag, so no change</h3>
<p><b>p</b> tag, and first-of-type of paragraph under this parent.</p>
</div>
</body>
</html>
以下示例演示了在 <ul> 父元素下的 <ul> 标记上使用 :first-of-type 伪类。
在此示例中,CSS 规则仅适用于在 <ul> 元素中找到的第一个 <li> 元素,而同一容器中的其他 <li> 元素不受影响。
<html>
<head>
<style>
ul li:first-of-type {
color: black;
background: yellow;
font-weight: 600;
font-size: 1em;
font-style: italic;
padding: 5px;
}
div {
border: 2px solid black;
margin-bottom: 5px;
width: 300px;
}
</style>
</head>
<body>
<div>
<ul>
<li>One</li>
<li>Two</li>
<li>Three
<ul>
<li>Three 1</li>
<li>Three 2</li>
<li>Three 3</li>
</ul>
</li>
</ul>
</div>
</body>
</html>