首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

:only-child

:only-childCSS伪类表示没有任何同胞元素的元素。这与:first-child:last-child:nth-child(1):nth-last-child(1)相同的,但具有较低的特异性。

代码语言:javascript
复制
/* Selects each <p>, but only if it is the */
/* only child of its parent */
p:only-child {
  background-color: lime;
}

注意:如最初定义的那样,所选元素必须有一个父元素。但从选择器级别4开始,这不再是必需的。

语法

代码语言:javascript
复制
:only-child

实例

基本实例

HTML

代码语言:javascript
复制
<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

代码语言:javascript
复制
main :only-child {
  color: red;
}

结果

列表示例

HTML

代码语言:javascript
复制
<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

代码语言:javascript
复制
li li {
  list-style-type: disc;
}
li:only-child {
  color: red;
  list-style-type: square;
}

结果

规范

Specification

Status

Comment

Selectors Level 4The definition of ':only-child' in that specification.

Working Draft

Matching elements are not required to have a parent.

Selectors Level 3The definition of ':only-child' in that specification.

Recommendation

Initial definition.

浏览器兼容性

Feature

Chrome

Edge

Firefox (Gecko)

Internet Explorer

Opera

Safari

Basic support

2

(Yes)

1.5 (1.8)

9

9.5

3.1

No parent required

57

?

?

?

44

?

Feature

Android Webview

Chrome for Android

Edge

Firefox Mobile (Gecko)

IE Mobile

Opera Mobile

Safari Mobile

Basic support

(Yes)

(Yes)

(Yes)

1.0 (1.8)

9

10

3.1

No parent required

57

57

?

?

?

44

?

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com