:only-child CSS 伪类表示没有任何兄弟元素的元素。这与 :first-child:last-child 或 :nth-child(1):nth-last-child(1) 相同,但前者具有更小的权重性。
CSS Demo: :only-child
li:only-child {
color: fuchsia;
}
b:only-child {
text-decoration: underline;
}
<p>Stars expected to attend:</p>
<ol>
<li>Robert Downey, Jr.</li>
</ol>
<p>Stars yet to confirm:</p>
<ol>
<li>Scarlett Johansson</li>
<li>Samuel L. Jackson</li>
<li>Chris Pratt</li>
</ol>
<p>The ceremony is going to be held in <b>The Dolby Theatre</b>.</p>
[!NOTE] 按照最初的定义,被选择的元素必须拥有一个父级元素。从选择器 Level 4 开始,这不再是必须的了。
语法
:only-child {
/* ... */
}
示例
基础示例
HTML
<div>
<div>我是唯一子元素。</div>
</div>
<div>
<div>我是第一个兄弟元素。</div>
<div>我是第二个兄弟元素。</div>
<div>
我是第三个兄弟元素。
<div>但这又是唯一的子元素。</div>
</div>
</div>
CSS
div:only-child {
color: red;
}
div {
display: inline-block;
margin: 6px;
outline: 1px solid;
}
结果
基础示例
一个列表示例
HTML
<ol>
<li>
第一
<ul>
<li>该列表仅有一个元素。</li>
</ul>
</li>
<li>
第二
<ul>
<li>该列表有三个元素。</li>
<li>该列表有三个元素。</li>
<li>该列表有三个元素。</li>
</ul>
</li>
</ol>
CSS
li li {
list-style-type: disc;
}
li:only-child {
color: red;
list-style-type: square;
}
结果
一个列表示例
规范
浏览器兼容性
参见
- :only-of-type
- :first-child
- :last-child
- :nth-child
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
