:only-child
Published on
Sometimes, you might want to change the styling of an element if it doesn’t have any siblings, and that’s super easy to do with the :only-child
pseudo-class.
This can be useful with dynamic content, where you might want to change the look if there is only one child, or if you have something like a <figure>
, where you might want to style it differently on whether or not there is or isn’t a <figcaption>
.
figure {
border-radius: 16px;
padding: 4px;
border: 1px solid black;
}
figure > img {
border-radius: 12px 12px 0 0;
}
figure > figcaption {
padding: 6px;
border-radius: 0 0 12px 12px;
}
figure > img:only-child {
border-radius: 12px;
}
And you could go the other way around with a :not(:only-child)
as well.
More recently, I’ve found combining it with :has()
can be very useful, where we can check if an element only has one child:
/* Cards with a single item get extra padding */
.card:has(> :only-child) {
padding: 2rem;
}
/* Cards with multiple children keep standard padding */
.card {
padding: 1rem;
}