: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.

* Some parts of this feature may have varying levels of support.

:first-child CSS 伪类表示在一组兄弟元素中的第一个元素。

尝试一下

语法

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

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
:first-child
Matches elements with no parent

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support

参见