Treehouse: Grow your CSS skills. Land your dream job.

:only-of-type

Last updated on:

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. 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?

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```