:only-child CSS Pseudo Class
Description
The :only-child pseudo-class in CSS is used to select an element that is the sole child of its parent. It allows developers to target elements that do not have any siblings, making it particularly useful for styling layouts where the appearance of a single item should differ from items in a group. This pseudo-class is dynamic, meaning it automatically updates if the DOM changes and the element is no longer the only child.
Unlike other pseudo-classes such as :first-child or :last-child, which target elements based on their position relative to siblings, :only-child requires that there be exactly one child element within the parent container. It is often used in combination with other selectors to apply specific styling rules only when an element stands alone, avoiding unintended effects when multiple sibling elements are present.
For example, consider a list where you want a single list item to have a different background when it is the only item:
<ul>
<li>Single item</li>
</ul>
li:only-child {
background-color: lightblue;
padding: 10px;
border-radius: 5px; /* Example of using a CSS property */
}
In this example, the <li> element receives a unique background because it is the only child within the <ul> element. If another <li> is added, the style from :only-child will no longer apply.
The :only-child pseudo-class can also be used with type selectors to be more specific. For instance, you can style only paragraphs that are the sole child of their parent container:
p:only-child {
font-style: italic;
}
Here, if a <p> element is the only child inside a <div> or any other container, it will be italicized. Otherwise, no styling is applied. This allows precise control over singular elements, often in combination with other CSS properties like margin, padding, or display.
Additionally, :only-child works well in responsive designs. For example, you could hide or adjust the layout of a single item differently than multiple items, ensuring the design scales correctly across different screen sizes.
Syntax
:only-child {
/* ... */
}
Example
Browser Support
The following information will show you the current browser support for the CSS :only-child pseudo class. Hover over a browser icon to see the version that first introduced support for this CSS psuedo class.
This psuedo class is supported by all modern browsers.
Desktop
Tablets & Mobile
Last updated by CSSPortal on: 31st December 2025
