How to use the 'Only-of-Type' Pseudo-Class
The only-of-type
pseudo-class is lesser-known but can be useful in CSS.
Let’s dive into a more detailed example to understand its functionality better.
What does it do?
The only-of-type
pseudo-class in CSS is a selector that targets an element that is the only sibling of its type within its parent container. It’s like giving a special style to an element that’s the only one of its kind in a group.
For a clearer understanding, let’s consider a blog post scenario. We’ll have a section with a heading, some paragraphs, and images.
We will use only-of-type
to style an image differently if it's the only image in the article. In this instance, we can highlight it in a green border if it's the only image in the article:
HTML Code:
<article> <h2>My Blog Post</h2> <p>Here's some introductory text about my blog post.</p> <img src="unique-image.jpg" alt="Unique Image"> <p>More details about the topic discussed in the blog post.</p> <!-- Uncomment to see the change <img src="another-image.jpg" alt="Another Image"> --> </article>
CSS Code:
img:only-of-type { border: 3px solid green; display: block; margin: auto; }
And so you can play with it, here's a CodePen with some slight variations so you can play with it:
In the HTML, the <article>
element contains a mixture of <h2>
, <p>
, and <img>
elements. The CSS targets any <img>
element that’s the only one of its kind within its parent <article>
and applies a green border.
So you'll notice in the CodePen that our second article on the page gets different styles because it's not the only image inside a tag.
Use cases for 'only-of-type'
This pseudo-class shines in scenarios where the presence or number of certain elements can vary. For instance, in a product listing, if there's only one featured product, you might want to highlight it differently than when there are several.
This pseudo-class is about recognizing and styling that one-of-a-kind element in a group!
Happy coding! ☘️