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
.
<ul> <li>I'm all alone!</li> </ul> <ul> <li>We are together.</li> <li>We are together.</li> <li>We are together.</li> </ul>
ul { border: 1px solid #ccc; margin: 20px; padding: 10px 10px 10px 30px; } li:only-of-type { color: red; }
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.
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
Browser Support
Chrome | Safari | Firefox | Opera | IE | Android | iOS |
---|---|---|---|---|---|---|
Any | Any | Any | Any | IE9+ | Any | Any |
Leave a Reply