Do you know about the :empty selector in CSS?
With so many properties and selectors available, it's easy to see why CSS can sometimes seem overwhelming. But if you take time to learn each of them with real use cases, you will know what to use when.
The :empty
selector is one such concept. This selector matches elements that have no content or children elements. Sounds simple, but if you don’t know its use case, you’ll easily forget its existence.
Let’s assume we need to show a success alert message on our page when something works. This is what the alert looks like.
The markup:
CSS:
This works great when there’s a success message. But when there’s no success event, there’s no message. What happens to the alert? This is what we see:
This is surely not desirable. We would want the entire block to disappear when there’s no message. Of course, we usually handle this situation in JavaScript, but with the :empty
selector, you don’t have to.
Simply do this:
And that’s it. You won’t see that block when its empty! So much cleaner right? Check out the demo for yourself.
📘 Complete Guide to CSS Flex and Grid
If you loved this write-up and how it was explained, you’ll absolutely love my eBook CSS Flex and Grid. Check it out!
📨 Newsletter suggestion
I love Tailwind CSS. If you love it too, I highly recommend subscribing to this one 👇
Tailwind Weekly: Weekly newsletter about all things Tailwind CSS. New issue every Saturday.
excellent