The :only-child
CSS pseudo-class represents an element without any siblings. This is the same as :first-child:last-child
or :nth-child(1):nth-last-child(1)
, but with a lower specificity.
/* Selects each <p>, but only if it is the */ /* only child of its parent */ p:only-child { background-color: lime; }
Note: As originally defined, the selected element had to have a parent. Beginning with Selectors Level 4, this is no longer required.
Syntax
:only-child
Examples
Basic example
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
div:only-child { color: red; } div { display: inline-block; margin: 6px; outline: 1px solid; }
Result
A list example
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
li li { list-style-type: disc; } li:only-child { color: red; list-style-type: square; }
Result
Specifications
Specification | Status | Comment |
---|---|---|
Selectors Level 4 The definition of ':only-child' in that specification. |
Working Draft | Matching elements are not required to have a parent. |
Selectors Level 3 The definition of ':only-child' in that specification. |
Recommendation | Initial definition. |
Browser compatibility
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
:only-child | Chrome Full support 2 | Edge Full support 12 | Firefox Full support 1.5 | IE Full support 9 | Opera Full support 9.5 | Safari Full support 3.1 | WebView Android Full support ≤37 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 3.1 | Samsung Internet Android Full support 1.0 |
Matches elements with no parent | Chrome Full support 57 | Edge Full support 79 | Firefox Full support 52 | IE No support No | Opera Full support 44 | Safari No support No | WebView Android Full support 57 | Chrome Android Full support 57 | Firefox Android Full support 52 | Opera Android Full support 43 | Safari iOS No support No | Samsung Internet Android Full support 7.0 |
Legend
- Full support
- Full support
- No support
- No support