This pseudo-class is not a new one, has been around for a while, however, I never had a chance to implement it, recently I had a scenario where I had dynamic content pulled out, and based on that, I had to style the images either square or round based on the number, different styling it if is only one or more than one. Here’s how I solved it using the CSS :only-of-type selector.
The thing was that the images start with a square shape. However, when there’s only one image, the :only-of-type
selector applies, giving it a rounded shape with border-radius: 50%
.
Demo Time:
See the Pen Untitled by Ivo Culic (@ifkas) on CodePen.
The beauty of this solution was simplicity and efficiency:
- No need for JavaScript to change styles based on the number of images.
- No need for additional classes or complex selectors.
- The styling automatically adjusts as images are added or removed.
Additional tip: the :only-of-type
as selector can be chained with other selectors such as :hover
and with pseudo-elements such as ::after
, among others.
When to use the CSS :only-of-type selector
- Dynamic Content: If your content is dynamic and you want to style an element differently when it’s the only one of its type.
- Specific Styling Needs: When you need to apply styles only when an element is unique within its parent.
- Avoiding Overspecificity: It can be useful in complex stylesheets to avoid overriding other styles unintentionally.
Next time you find yourself reaching for JavaScript to handle conditional styling based on element count, remember the :only-of-type selector – it might just be the simple solution you need.
Learn more: https://developer.mozilla.org/en-US/docs/Web/CSS/:only-of-type