CSS :only-of-type
Pseudo-Class
The :only-of-type
pseudo-class selects an element if it is the only one of its type within its parent. This is useful when you want to apply styles to elements with no siblings of the same type.
1. Syntax
✅ Targets an element only if it's the sole occurrence of its tag within its parent.
2. Example – Highlighting Unique Elements
✅ Only the <p>
inside the first <div>
is styled because it's the only paragraph there.
❌ The second <div>
has two <p>
elements, so neither gets styled.
3. Use Case – Styling Unique List Items
✅ The first <li>
gets a yellow background since it's the only <li>
inside its <ul>
.
❌ The second <ul>
has multiple <li>
elements, so none get styled.
4. :only-of-type
vs. :only-child
Pseudo-Class | Applies To | Condition |
---|---|---|
:only-of-type | Any element | The only one of its type inside the parent. |
:only-child | Any element | The only child (of any type) inside the parent. |
Example
✅ The paragraph gets styled as :only-of-type
(it's the only <p>
).
❌ It doesn't match :only-child
because there's a <span>
inside the parent.
5. Browser Support
✅ Fully supported in Chrome, Edge, Firefox, Safari, and Opera.
6. Best Practices
✔ Use :only-of-type
to target unique elements without extra classes.
✔ Combine with :nth-child()
or :first-of-type
for more precise control.
✔ Works great for responsive designs and dynamic content.