CSS :only-of-type Pseudo Class

CSS :only-of-type Pseudo Class

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

selector:only-of-type { /* Styles for the only element of its type */ }

✅ Targets an element only if it's the sole occurrence of its tag within its parent.

2. Example – Highlighting Unique Elements

<div> <p>This paragraph is inside a div.</p> </div> <div> <p>This paragraph is inside another div.</p> <p>Another paragraph in the same div.</p> </div>
p:only-of-type { color: red; font-weight: bold; }

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

<ul> <li>Item 1</li> </ul> <ul> <li>Item A</li> <li>Item B</li> </ul>
li:only-of-type { background-color: yellow; }

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

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