CSS Reference ยท Pseudo-classes
The :only-of-type pseudo-class
Reference for the CSS :only-of-type pseudo-class: select an element that has no siblings with the same tag name, with live examples and usage notes.
The :only-of-type pseudo-class matches an element that is the only child of its parent with that tag name. Siblings with other tag names do not matter. It is the same as combining :first-of-type and :last-of-type on one element.
Use it when the same element can appear once or many times, and the lone case needs different styling: a single figure in an article, one <img> in a card, or a single list in a section.
img:only-of-type { width: 100%; }
Try it
The first and third cards each contain exactly one <span>, so both are highlighted even though they also contain <em> siblings. The middle card has two spans, so neither matches.
Syntax
:only-of-type { /* declarations */ }
- Arguments: none.
- Specificity: a pseudo-class, so it adds (0, 1, 0).
- Matches: an element whose parent has no other child element with the same tag name (and namespace).
Values
| Syntax and arguments | Description |
|---|---|
:only-of-type |
No arguments. Matches an element with no same-type siblings. |
tag:only-of-type |
The usual form: restricts the check to one tag, such as p:only-of-type. |
Usage notes
- Type means tag name.
<div class="a">and<div class="b">are the same type. Classes do not create separate types. - Text nodes are ignored. Only elements are counted, so loose text beside the element does not stop a match.
- Compare with
:only-child.:only-childrequires that there are no other elements at all.:only-of-typeallows siblings of other tags. - Without a tag name it matches many elements. A bare
:only-of-typematches the first<h2>, the only<ul>, and so on, all at once. Add a type selector to keep the rule focused. - It reacts to content changes. Add a second sibling of the same tag and the match disappears, which makes it handy for components with a variable number of items.
Browser support
Supported in every browser, including very old ones.
Related
:only-childโ the only element child:first-of-typeโ first sibling of its type:last-of-typeโ last sibling of its type:nth-of-type()โ position among siblings of one type- Lesson: Structural Pseudo-classes