CSS 伪类选择器 :first-child 用于在一组同级元素中选择第一个子元素并设置其样式。
语法
:first-child {
/* ... */
}
CSS :first-child 示例
以下示例演示了在 <div> 父元素下的 <p> 标记上使用 :first-child 伪类。
在此示例中,CSS 规则仅适用于在 <div> 元素中找到的第一个 <p> 元素,而同一容器中的其他 <p> 元素不受影响。
<html>
<head>
<style>
p:first-child {
color: black;
background: yellow;
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-child 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, but not the first child.</p>
</div>
</body>
</html>
以下示例演示了在 <li> 标记的父元素下的 <ul> 下的 :first-child 伪类的使用。
在此示例中,CSS 规则仅适用于在 <ul> 元素中找到的第一个 <li> 元素,而同一容器中的其他 <li> 元素不受影响。
<html>
<head>
<style>
ul li:first-child {
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>