CSS Reference Pseudo-class

:only-of-type 1q2m70

:only-of-type is a CSS pseudo-selector which matches an element if its parent has no other children of the same type. 2zb3v

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>
                

:only-of-type is similar to the :only-child in its entry.

Just like other pseudo-class selectors, the :only-of-type selector can be chained with other selectors 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 3e5p5z

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 2x4j2k

In the following demo, :only-of-type is used to style links and h1s and paragraphs that are the only children of their type inside their container.

View this demo on the Codrops Playground

Browser k5t66

The :only-of-type pseudo-class selector is ed in Chrome, Firefox, Safari, Opera 9.5+, Internet Explorer 9+, and on Android and iOS.

Written by

Last updated June 3, 2020 at 12:33 pm by Mary Lou

Do you have a suggestion, question or want to contribute? Submit an issue.