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>234</div>
<div>abc</div>
<div></div>
<div>def</div>
</div>
That empty div gets displayed in the UI just like the others:, empty box.
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.
🐘 A lot of developers will reach for JavaScript manipulation for stuff like this.
If you enjoyed this article, you may also like Dervic Blog's.
Comments (0)