--- title: ':only-child' slug: 'Web/CSS/:only-child' tags: - CSS - Layout - Pseudo-class - Reference - Web translation_of: 'Web/CSS/:only-child' ---
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 开始, 这不再是必须的了.
<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>
main :only-child { color: red; }
{{EmbedLiveSample('基础示例','100%',180)}}
<ol> <li>First <ul> <li>This list has just one element.</li> </ul> </li> <li>Second <ul> <li>This list has three elements.</li> <li>This list has three elements.</li> <li>This list has three elements.</li> </ul> </li> </ol>
li li { list-style-type: disc; } li:only-child { color: red; list-style-type: square; }
{{EmbedLiveSample('一个列表示例', '100%', 210)}}
Specification | Status | Comment |
---|---|---|
{{SpecName('CSS4 Selectors', '#only-child-pseudo', ':only-child')}} | {{Spec2('CSS4 Selectors')}} | Matching elements are not required to have a parent. |
{{SpecName('CSS3 Selectors', '#only-child-pseudo', ':only-child')}} | {{Spec2('CSS3 Selectors')}} | Initial definition. |
{{Compat("css.selectors.only-child")}}