CSS伪类:only-child代表了属于某个父元素的唯一一个子元素.等效的选择器还可以写成 :first-child:last-child或者:nth-child(1):nth-last-child(1),当然,前者的权重会低一点.

/* Selects each <p>, but only if it is the */
/* only child of its parent */
p:only-child {
  background-color: lime;
}

Note: 在起初定义, 被选择的元素必须拥有一个父级元素. 从 Selectors Level 4 开始, 这不再是必须的了.

语法

:only-child

示例

基础示例

HTML

<main>
  <div>
    <i>I am a lonely only child.</i>
  </div>

  <div>
    <i>I have siblings.</i><br>
    <b>So do I!</b><br>
    <span>I also have siblings, <span>but this is an only child.</span></span>
  </div>
</main>

CSS

main :only-child {
  color: red;
}

结果

一个列表示例

HTML

<ol>
  <li>First
    <ul>
      <li>This list has just one element.
    </ul>
  </li>
  <li>Second
    <ul>
      <li>This list has three elements.
      <li>This list has three elements.
      <li>This list has three elements.
    </ul>
  </li>
<ol>

CSS

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

结果

规范

Specification Status Comment
Selectors Level 4
:only-child
Working Draft Matching elements are not required to have a parent.
Selectors Level 3
:only-child
Recommendation Initial definition.

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung Internet
Basic supportChrome Full support 2Edge Full support YesFirefox Full support 1.5IE Full support 9Opera Full support 9.5Safari Full support 3.1WebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support 10Safari iOS Full support 3.1Samsung Internet Android Full support Yes
Matches elements with no parentChrome Full support 57Edge ? Firefox Full support 52IE ? Opera Full support 44Safari ? WebView Android Full support 57Chrome Android Full support 57Edge Mobile ? Firefox Android Full support 52Opera Android Full support 44Safari iOS ? Samsung Internet Android Full support 7.0

Legend

Full support  
Full support
Compatibility unknown  
Compatibility unknown

另见

文档标签和贡献者

此页面的贡献者: Jiang-Xuan, teoli, ziyunfei
最后编辑者: Jiang-Xuan,