:only-of-type

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

Comments

  1. User Avatar
    heike
    Permalink to comment#

    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?

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

Submit a Comment

icon-closeicon-emailicon-linkicon-menuicon-searchicon-tag