DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!
The :only-of-type
pseudo-class selector in CSS represents any element that has no siblings of the given type.
p:only-of-type {
color: red;
}
If no tag precedes the selector, it will match any tag (e.g. :only-of-type
). If another selector precedes it, it will matched based on the type of tag that selector matches. For example .example:only-of-type
will behave like p:only-of-type
if .example
is applied to a paragraph element.
Simple Example
One list contains only a single list item. Another list contains three list items. We can target the list item that is alone with :only-of-type
.
Check out this Pen!
Although perhaps that isn’t the best example, because :only-child
would work just as well there since list items are the only possible children of lists. If we use divs instead, we could target a paragraph inside a div if it’s the only paragraph, despite other elements being in there as well.
Check out this Pen!
To Note
As a fun aside, you could achieve the same selection as :only-of-type
with :first-of-type:last-of-type
or :nth-of-type(1):nth-last-of-type(1)
. Those use two chained selectors though, meaning the specificity is double that of :only-of-type
.
Related Properties
Other Resources
Browser Support
Chrome | Safari | Firefox | Opera | IE | Android | iOS |
---|---|---|---|---|---|---|
Any | Any | Any | Any | IE9+ | Any | Any |
First, thanks for publishing and sharing your knowledge, I could not work without!
I’ve used :only-of-type for the first time today and it applies to spans, p’s, img’s but not to div’s, is that right?