:only-of-type
is a CSS pseudo-selector which matches an element if its parent has no other children of the same type.
For example, p:only-of-type
will match a paragraph only if it is the only paragraph inside its parent. So, it will select the following paragraph:
<article> <h1>Heading</h1> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Soluta, enim, libero voluptatum id nostrum porro laborum error nisi fugit atque a possimus ullam maxime quia tenetur obcaecati dolorum dolore placeat. </p> </article>
Because it is the only paragraph in the article, but it will not match any of the following paragraphs, since none of them is the only paragraph inside their container:
<article> <h1>Heading</h1> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, iusto, eos similique eaque minus magni tempore repudiandae mollitia dignissimos obcaecati animi quis et impedit consectetur optio modi perferendis voluptate corporis! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, iusto, eos similique eaque minus magni tempore repudiandae mollitia dignissimos obcaecati animi quis et impedit consectetur optio modi perferendis voluptate corporis! </p> </article>
Trivia & Notes
:only-of-type
is similar to the :only-child
selector, except that the :only-child
selector selects the element if its parent has no other children of any type. You can read more about :only-child
in its entry.
Just like other pseudo-class selectors, the :only-of-type
selector can be chained with other selectors such as :hover
and with pseudo-elements such as ::after
, among others. For example, the following rule will add content to a link in a paragraph if it is the only link in that paragraph:
a:only-of-type::after { /* content and styles here */ }
Examples
The following are all valid :only-of-type
declarations:
article:only-of-type { /* styles */} span:only-of-type { /* styles */} a:only-of-type:hover { /* styles */} p:only-of-type a { /* styles */}
Live Demo
In the following demo, :only-of-type
is used to style links and h1
s and paragraphs that are the only children of their type inside their container.
Browser Support
The :only-of-type
pseudo-class selector is supported in Chrome, Firefox, Safari, Opera 9.5+, Internet Explorer 9+, and on Android and iOS.