:only-child CSS Pseudo Class
Description
The :only-child
pseudo-class in CSS is a selector that targets elements that are the only child of their parent element. In other words, it selects elements that have no siblings within the same parent element. This pseudo-class is useful for styling specific elements when they are the only child, allowing developers to apply unique styles to such elements without affecting other elements within the same parent.
For example, consider the following HTML structure:
<div>
<p>First child paragraph</p>
</div>
<div>
<p>Second child paragraph</p>
<p>Third child paragraph</p>
</div>
Using the
:only-child
pseudo-class, you can style the first <p>
element because it is the only child of its parent <div>
:div p:only-child {
color: blue;
font-weight: bold;
}
In this case, the
:only-child
pseudo-class targets the first <p>
element and styles it with blue color and bold font weight because it is the only child of its parent <div>
. The second <div>
contains multiple <p>
elements, so they are not affected by this CSS rule.
Syntax
:only-child { /* ... */ }
Example
<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>
div:only-child {
color: red;
}
div {
display: inline-block;
margin: 6px;
outline: 1px solid;
}
Browser Support
The following table will show you the current browser support for the CSS :only-child
pseudo class.
Desktop | |||||
12 | 2 | 1.5 | 9.5 | 3.1 |
Tablets / Mobile | |||||
18 | 4 | 10.1 | 2 | 1 | 37 |
Last updated by CSSPortal on: 1st October 2023