CSS

:only-child

:only-child

:only-childCSS伪类表示没有任何同胞元素的元素。这与: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; }

注意:如最初定义的那样,所选元素必须有一个父元素。但从选择器级别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; }

结果

规范

SpecificationStatusComment
Selectors Level 4The definition of ':only-child' in that specification.Working DraftMatching elements are not required to have a parent.
Selectors Level 3The definition of ':only-child' in that specification.RecommendationInitial definition.

浏览器兼容性

FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support2(Yes)1.5 (1.8)99.53.1
No parent required57???44?

FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support(Yes)(Yes)(Yes)1.0 (1.8)9103.1
No parent required5757???44?