:only-child
Quick Summary for :only-child
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.
Code Usage for :only-child
/* Selects each <p>, but only if it is the */ /* only child of its parent */ p:only-child { background-color: lime; }
More Details for :only-child
:only-child
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; }
ResultA 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; }
ResultSpecifications
Specification |
---|
Selectors Level 4 # only-child-pseudo |
See also
:only-of-type
:first-child
:last-child
:nth-child
Last modified: Jan 20, 2022, by MDN contributors
Select your preferred language English (US)DeutschEspañolFrançais日本語Português (do Brasil)Русский中文 (简体) Change language Posted in
12:22 am, February 22, 2022
Add Comment
Other Items in CSS
rgb()
rgba()
:right
right
@right-bottom
:root
rotate
rotate()
rotate3d()
rotateX()
rotateY()
rotateZ()
row-gap
ruby-align
ruby-position
saturate()
scale
scale()
scale3d()
scaleX()
scaleY()
scaleZ()
:scope
scroll-behavior
scroll-margin
scroll-margin-block
scroll-margin-block-end
scroll-margin-block-start
scroll-margin-bottom
scroll-margin-inline
scroll-margin-inline-end
scroll-margin-inline-start
scroll-margin-left
scroll-margin-right
scroll-margin-top
scroll-padding
scroll-padding-block
scroll-padding-block-end
scroll-padding-block-start
scroll-padding-bottom
scroll-padding-inline
scroll-padding-inline-end
scroll-padding-inline-start
scroll-padding-left
scroll-padding-right
scroll-padding-top
scroll-snap-align
scroll-snap-stop
scroll-snap-type
@scroll-timeline