DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!
The :only-child
pseudo-class selector property in CSS represents an element that has a parent element and whose parent element has no other element children. This would be the same as :first-child:last-child
or :nth-child(1):nth-last-child(1)
, but with a lower specificity.
div p:only-child {
color: red;
}
For example, if we nest paragraphs within a <div>
like so…
<div>
<p>This paragraph is the only child of its parent</p>
</div>
<div>
<p>This paragraph is the first child of its parent</p>
<p>This paragraph is the second child of its parent</p>
</div>
Now we can style the only <p>
of our first child <div>
. The subsequent <div>
and it’s children will never be styled as the parent container holds more than one child (i.e. the p tags).
p:only-child {
color:red;
}
We could also mixin additional pseudo-classes like this example that selects the first paragraph within our nested div and the only-child of div.contain
.
<div class="contain">
<div>
<p>Hello World</p>
<p>some more children</p>
</div>
</div>
div.contain div:only-child :first-child {
color: red;
}
:only-child
won’t work as a selector if your parent element contains more than one child with an identical tag. For example…
<div class="contain">
<div>
<h1>Div Child 1</h1>
<p>paragraph1</p>
<p>paragraph2</p>
</div>
<div>
<h1>Div Child 2</h1>
<p>paragraph1</p>
<p>paragraph2</p>
</div>
<div>
<h1>Div Child 3</h1>
<p>paragraph1</p>
<p>paragraph2</p>
</div>
</div>
div.contain div:only-child {
color: red;
}
This will result in no divs inheriting the color red as the parent contains more than 1 child (the 3 unnamed divs).
Related Properties
Other Resources
Browser Support
This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.
Desktop
Chrome | Firefox | IE | Edge | Safari |
---|---|---|---|---|
4 | 3.5 | 9 | 12 | 3.2 |
Mobile / Tablet
Android Chrome | Android Firefox | Android | iOS Safari |
---|---|---|---|
127 | 127 | 2.1 | 3.2 |
Thanks…! Very rare known property…
Hi,
how can I match this (when “strong” is the only child of “p” and “p” is without text ):
but not this (when “p” has text also):
Thank you very much!