唯一子偽類選擇器示例

:only-child CSS 偽類表示任何元素,它是其父元素的唯一子元素。

HTML:

<div>
  <p>This paragraph is the only child of the div, it will have the color blue</p>
</div>

<div>
  <p>This paragraph is one of the two children of the div</p>
  <p>This paragraph is one of the two children of its parent</p>
</div>

CSS:

p:only-child {
  color: blue;
}

上面的例子選擇了 <p> 元素,它是來自父元素的唯一子元素,在本例中是 <div>

JSBin 現場演示