blob: ec6835d20c1975eb14de0d3789dbf067d76c70ed (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
|
---
title: ':only-child'
slug: Web/CSS/:only-child
tags:
- CSS
- レイアウト
- 擬似クラス
- リファレンス
- セレクター
- ウェブ
browser-compat: css.selectors.only-child
translation_of: Web/CSS/:only-child
---
{{CSSRef}}
**`:only-child`** は [CSS](/ja/docs/Web/CSS) の[擬似クラス](/ja/docs/Web/CSS/Pseudo-classes)で、兄弟要素がない要素を表します。 `:first-child:last-child` または `:nth-child(1):nth-last-child(1)` と同じですが、詳細度はより低くなります。
```css
/* 親の唯一の子である <p> 要素をすべて選択 */
p:only-child {
background-color: lime;
}
```
> **Note:** 最初の定義では、親のある要素のみが選択されていました。 Selectors Level 4 の初期に、これは必要なくなりました。
## 構文
{{csssyntax}}
## 例
### 基本的な例
#### HTML
```html
<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>
```
#### CSS
```css
div:only-child {
color: red;
}
div {
display: inline-block;
margin: 6px;
outline: 1px solid;
}
```
#### 結果
{{EmbedLiveSample('Basic_example','100%',180)}}
### リストの例
#### HTML
```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
```css
li li {
list-style-type: disc;
}
li:only-child {
color: red;
list-style-type: square;
}
```
#### 結果
{{EmbedLiveSample('A_list_example', '100%', 210)}}
## 仕様書
{{Specifications}}
## ブラウザーの互換性
{{Compat}}
## 関連情報
- {{Cssxref(":only-of-type")}}
- {{Cssxref(":first-child")}}
- {{Cssxref(":last-child")}}
- {{Cssxref(":nth-child")}}
|