CSS :only-child Pseudo Class

CSS :only-child Pseudo Class

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

selector:only-child { /* Styles for elements that are the only child */ }

✅ Targets an element only if it's the single child of its parent.

2. Example – Styling a Unique Child

<div> <p>This paragraph is the only child.</p> </div> <div> <p>This paragraph has a sibling.</p> <span>This is a sibling element.</span> </div>
p:only-child { color: red; font-weight: bold; }

✅ 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

<ul> <li>Single item</li> </ul> <ul> <li>Item 1</li> <li>Item 2</li> </ul>
li:only-child { background-color: yellow; }

✅ 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-ClassApplies ToCondition
:only-childAny elementThe only child (of any type) inside its parent.
:only-of-typeAny elementThe only one of its type inside its parent.

Example

<div> <p>I'm the only paragraph.</p> <span>I prevent :only-child from working!</span> </div>
p:only-of-type { color: blue; } p:only-child { color: green; }

✅ 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.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close