:first-child
试一试
语法
css
:first-child {
/* ... */
}
示例
基本示例
HTML
html
<div>
<p>This text is selected!</p>
<p>This text isn't selected.</p>
</div>
<div>
<h2>This text isn't selected: it's not a `p`.</h2>
<p>This text isn't selected.</p>
</div>
CSS
css
p:first-child {
color: lime;
background-color: black;
padding: 5px;
}
结果
设置列表样式
HTML
html
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>
Item 3
<ul>
<li>Item 3.1</li>
<li>Item 3.2</li>
<li>Item 3.3</li>
</ul>
</li>
</ul>
CSS
css
ul li {
color: blue;
}
ul li:first-child {
color: red;
font-weight: bold;
}
结果
规范
规范 |
---|
选择器级别 4 # first-child-pseudo |
浏览器兼容性
BCD 表格仅在浏览器中加载