CSS参考手册
选择 | Selectors
:only-child
该:only-child
CSS伪类表示没有任何同胞元素的元素。这与: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;
}
结果
规范
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 |
? |
选择 | Selectors相关
层叠样式表( Cascading Style Sheets )是一种用来表现 HTML 或 XML 等文件样式的计算机语言。CSS 不仅可以静态地修饰网页,还可以配合各种脚本语言动态地对网页各元素进行格式化。