:only-of-type CSS Pseudo Class
Description
The :only-of-type
pseudo-class is a CSS selector that targets an element when it is the only child of its parent element with the same element type. In other words, it selects an element if there are no other sibling elements of the same type within the same parent container. This pseudo-class is particularly useful for applying styles to elements that are unique within their parent's context.
Here's a basic example of how you might use :only-of-type
in CSS:
p:only-of-type {
font-weight: bold;
color: blue;
}
In this example, the CSS rules will apply to
<p>
elements that are the only <p>
element within their parent container, making them bold and changing their text color to blue. If there are multiple <p>
elements within the same parent, the styles won't apply to any of them.
Syntax
:only-of-type { /* ... */ }
Example
<main>
<div>I am 'div' #1.</div>
<p>I am the only 'p' among my siblings.</p>
<div>I am 'div' #2.</div>
<div>I am 'div' #3.
<i>I am the only 'i' child.</i>
<em>I am 'em' #1.</em>
<em>I am 'em' #2.</em>
</div>
</main>
main :only-of-type {
color: red;
}
Browser Support
The following table will show you the current browser support for the CSS :only-of-type
pseudo class.
Desktop | |||||
12 | 1 | 3.5 | 9.5 | 3.1 |
Tablets / Mobile | |||||
18 | 4 | 10.1 | 2 | 1 | 2 |
Last updated by CSSPortal on: 1st October 2023