CSS Reference ยท Pseudo-classes
The :only-child pseudo-class
Reference for the CSS :only-child pseudo-class: select an element with no sibling elements, with syntax, examples, common mistakes and browser support.
The :only-child pseudo-class matches an element that has no sibling elements: it is both the first and the last child of its parent. It is the same as :first-child:last-child.
It lets you style the "single item" case differently, for instance a list that has only one entry, without counting items in JavaScript.
li:only-child { list-style: none; }
Try it
Syntax
:only-child { /* declarations */ }
No arguments; specificity (0,1,0). Text nodes do not count, so an element with surrounding text but no sibling elements still matches.
Syntax and arguments
| Part | Description |
|---|---|
:only-child |
Matches an element that is the sole child element of its parent. |
| No arguments | The pseudo-class is not functional. |
| Equivalent | :first-child:last-child |
| By tag name | Use :only-of-type to ignore siblings of other tags. |
Usage notes
- Empty states. It is a quick way to style a lone item, such as hiding a "remove" button when only one row is left.
- Dynamic content. The match turns on and off as items are added or removed, with no script needed.
- Other tags count.
p:only-childfails if a heading or image sits beside the paragraph; usep:only-of-typewhen only the same tag matters. - Beware of wrappers. A line break or icon element beside your item makes it no longer the only child.
- Pair with
:not().li:not(:only-child)styles every item in lists of two or more.
Browser support
Supported in every browser.
Related
:first-childโ first sibling:last-childโ last sibling:first-of-typeโ first of its tag name- Lesson: Structural pseudo-classes