:only-child and :only-of-type
What you'll learn: How to style elements that appear alone—either as the sole child of their parent or the only one of their element type.
Understanding These Selectors
Sometimes an element stands alone, and you want to style it differently when it does. The :only-child and :only-of-type pseudo-classes let you target these unique situations automatically.
:only-child matches an element that is the only child of its parent—no siblings at all.
:only-of-type matches an element that is the only one of its type among its siblings—other siblings may exist, but none share the same tag name.
When to Use Them
Think of a product card that might contain one image or several. If there's only one image, you might want it centered with extra padding. If there are multiple, you'd want them in a grid.
/* Single image gets special treatment */
.product img:only-child {
display: block;
margin: 0 auto;
max-width: 100%;
}
/* Only paragraph of its type gets larger text */
.intro p:only-of-type {
font-size: 1.2rem;
text-align: center;
}
The Key Difference
:only-child is stricter—the element must be completely alone. :only-of-type is more flexible—it can have siblings, as long as they're different elements.
<!-- img is :only-child AND :only-of-type -->
<div><img src="photo.jpg"></div>
<!-- p is :only-of-type but NOT :only-child -->
<div>
<p>Text here</p>
<img src="photo.jpg">
</div>
Key Takeaway: Use :only-child to style elements with no siblings at all, and :only-of-type to style elements that are the sole instance of their tag among siblings—perfect for automatically adjusting spacing and layout based on content.