How to check if there is only one child element using CSS

April 7, 2020

Recently at work I had a situation where I needed to style an element one way if it was the only element present, and another way if it had sibling elements.

I scratched my head and did what I always do, Google it.

And that's when it happened...I learned about the :only-child selector!!

My mind was blown.

Then I realized if you combine it with the :not() selector, you can check if it has any siblings.

.my-element:only-child {
    /* The only element  */

.my-element:not(:only-child) {
    /* NOT the only element */

.selector:only-of-type {

And the support for :only-child is amazing. Green across the board.