:first-child
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
尝试一下
语法
css
:first-child {
/* ... */
}
示例
基础示例
HTML
html
<div>
<p>此文本已选中!</p>
<p>此文本未选中。</p>
</div>
<div>
<h2>此文本未被选中:它不是一个 `p`。</h2>
<p>此文本未被选中。</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;
}
结果
规范
Specification |
---|
Selectors Level 4 # first-child-pseudo |
浏览器兼容性
BCD tables only load in the browser