:only-child - CSS(层叠样式表) 编辑
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.</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>
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. |
浏览器兼容性
BCD tables only load in the browser
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.另见
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论