:only-child CSS Pseudo Class

If this site has been useful, we’d love your support! Running this site takes time and resources, and every small contribution helps us keep creating valuable content. Consider buying us a coffee to keep things going strong!

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
Edge Chrome Firefox Opera Safari
1221.59.53.1
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
18410.12137

Last updated by CSSPortal on: 1st October 2023