:only-child

2 位贡献者:

概述

CSS伪类:only-child代表了属于某个父元素的唯一一个子元素.等效的选择器还可以写成 :first-child:last-child或者:nth-child(1):nth-last-child(1),当然,前者的权重会低一点.

语法

parent child:only-child {
  property: value;
} 

示例

一个基础示例

span:only-child {
  color: red;
}
<div>
    <span>This span is the only child of its father</span>
</div>

<div>
    <span>This span is one of the two children of its father</span>
    <span>This span is one of the two children of its father</span>
</div> 

演示结果

This span is the only child of its father
This span is one of the two children of its father This span is one of the two children of its father
This span is the only child of its father
This span is one of the two children of its father This span is one of the two children of its father

一个列表示例

li li {
  list-style-type: disc;
}
li:only-child {
  color: #6699ff;
  font-style: italic;
  list-style-type: square;
}
<ol>
    <li>First
        <ul>
            <li>This is only child element
        </ul>
    </li>
    <li>Second
        <ul>
            <li>This list has two elements
            <li>This list has two elements
        </ul>
    </li>
    <li>Third
        <ul>
            <li>This list has three elements
            <li>This list has three elements
            <li>This list has three elements
        </ul>
    </li>
<ol>
  1. First
    • This list has only one element
  2. Second
    • This list has two elements
    • This list has two elements
  3. Third
    • This list has three elements
    • This list has three elements
    • This list has three elements

p:only-child {
    background: #6699ff;
    width: 350px;
}
<div>
    <p>This is a paragraph with :only-child</p>
</div>

This is a paragraph with :only-child

规范

Specification Status Comment
Selectors Level 4 Working Draft No change.
Selectors Level 3 Recommendation Initial definition.

浏览器兼容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 2 1.5 (1.8) 9 9.5 3.1
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 2.1 1.0 (1.8) 9 10.0 3.1

 

文档标签和贡献者

向此页面作出贡献: teoli, ziyunfei
最后编辑者: teoli,