CSS :only-child Pseudo-Class
The :only-child pseudo-class selects an element if it is the only child of its parent. This means the parent must not have any other elements inside it.
1. Syntax
✅ Targets an element only if it's the single child of its parent.
2. Example – Styling a Unique Child
✅ The first paragraph is red because it's the only child of <div>.
❌ The second paragraph is not affected because the <span> prevents it from being an only child.
3. Example – Styling Unique List Items
✅ The first <li> gets a yellow background because it’s the only child of <ul>.
❌ The second <ul> has multiple <li> elements, so none are styled.
4. :only-child vs. :only-of-type
| Pseudo-Class | Applies To | Condition |
|---|---|---|
:only-child | Any element | The only child (of any type) inside its parent. |
:only-of-type | Any element | The only one of its type inside its parent. |
Example
✅ The <p> is styled with :only-of-type because it’s the only <p> inside <div>.
❌ The <p> is not affected by :only-child because the <span> prevents it.
5. Browser Support
✅ Fully supported in Chrome, Edge, Firefox, Safari, and Opera.
6. Best Practices
✔ Use :only-child for targeting unique children without extra classes.
✔ Combine with :first-child or :nth-child() for more precise control.
✔ Works well for dynamic content where elements may be added or removed.

