This content originally appeared on Go Make Things and was authored by Go Make Things
One of my favorite not-so-new aspects of CSS is the :empty
pseudo-class.
You can use this to target elements that have no children—either child elements or whitespace and text nodes—and style them differently than they would be otherwise.
For example, imagine you have some CSS to layout items in a row using flexbox…
.grid-flex {
display: flex;
gap: 1rem;
}
.grid-flex > div {
background-color: #ffdc00;
border: 1px solid #665800;
color: #665800;
padding: 1rem 2rem;
text-align: center;
}
And a row of items generated from an API or database or something.
Since you don’t know the content ahead of time, it’s possible that one of the items may have no content in it, like the fourth <div>
the .grid-flex
container below…
<div class="grid-flex">
<div>1</div>
<div>234567890</div>
<div>abc</div>
<div></div>
<div>def</div>
</div>
That empty div
gets displayed in the UI just like the others: a big yellow, empty box. Here’s a demo.
In situations like this, you can use the :empty
pseudo-class to hide elements that might not have any content, but could end up in the UI when they shouldn’t.
.grid-flex > div:empty {
display: none;
}
Now, the empty yellow box is hidden in the UI. Here’s another demo.
A lot of developers will reach for JavaScript DOM manipulation for stuff like this. But CSS provides a simpler, easier, and less error-prone way to handle the same thing.
Like this? A Lean Web Club membership is the best way to support my work and help me create more free content.
This content originally appeared on Go Make Things and was authored by Go Make Things

Go Make Things | Sciencx (2025-01-09T14:30:00+00:00) The :empty pseudo-class in CSS. Retrieved from https://www.scien.cx/2025/01/09/the-empty-pseudo-class-in-css/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.