--- title: ':only-child' slug: 'Web/CSS/:only-child' tags: - CSS - ウェブ - セレクター - リファレンス - レイアウト - 擬似クラス translation_of: 'Web/CSS/:only-child' ---
CSS の :only-child 疑似クラスは、兄弟要素がない要素を表します。 :first-child:last-child または :nth-child(1):nth-last-child(1) と同じですが、詳細度はより低くなります。
/* 親の唯一の子である <p> 要素をすべて選択 */
p:only-child {
background-color: lime;
}
メモ: 最初の定義では、親のある要素のみが選択されていました。 Selectors Level 4 の初期に、これは必要なくなりました。
<div> <div>I am an only child.</div> </div> <div> <div>I am the 1st sibling.</div> <div>I am the 2nd sibling.</div> <div>I am the 3rd sibling, <div>but this is an only child.</div></div> </div>
div:only-child {
color: red;
}
div {
display: inline-block;
margin: 6px;
outline: 1px solid;
}
{{EmbedLiveSample('Basic_example','100%',180)}}
<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>
li li {
list-style-type: disc;
}
li:only-child {
color: red;
list-style-type: square;
}
{{EmbedLiveSample('A_list_example', '100%', 210)}}
| 仕様書 | 状態 | 備考 |
|---|---|---|
| {{SpecName('CSS4 Selectors', '#only-child-pseudo', ':only-child')}} | {{Spec2('CSS4 Selectors')}} | 選択する要素に親を必要としないようにした。 |
| {{SpecName('CSS3 Selectors', '#only-child-pseudo', ':only-child')}} | {{Spec2('CSS3 Selectors')}} | 初回定義 |
{{Compat("css.selectors.only-child")}}