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

:only-child CSS 伪类表示没有任何兄弟元素的元素。这与 :first-child:last-child:nth-child(1):nth-last-child(1) 相同,但前者具有更小的权重性。

尝试一下

备注: 按照最初的定义,被选择的元素必须拥有一个父级元素。从选择器 Level 4 开始,这不再是必须的了。

语法

css
:only-child {
  /* ... */
}

示例

基础示例

HTML

html
<div>
  <div>我是唯一子元素。</div>
</div>

<div>
  <div>我是第一个兄弟元素。</div>
  <div>我是第二个兄弟元素。</div>
  <div>
    我是第三个兄弟元素。
    <div>但这又是唯一的子元素。</div>
  </div>
</div>

CSS

css
div:only-child {
  color: red;
}

div {
  display: inline-block;
  margin: 6px;
  outline: 1px solid;
}

结果

一个列表示例

HTML

html
<ol>
  <li>
    第一
    <ul>
      <li>该列表仅有一个元素。</li>
    </ul>
  </li>
  <li>
    第二
    <ul>
      <li>该列表有三个元素。</li>
      <li>该列表有三个元素。</li>
      <li>该列表有三个元素。</li>
    </ul>
  </li>
</ol>

CSS

css
li li {
  list-style-type: disc;
}

li:only-child {
  color: red;
  list-style-type: square;
}

结果

规范

Specification
Selectors Level 4
# only-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
:only-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

参见