CSS Simplified

Share this post

Do you know about the :empty selector in CSS?

shrutibalasa.substack.com

Do you know about the :empty selector in CSS?

Shruti Balasa
Feb 1
5
2
Share this post

Do you know about the :empty selector in CSS?

shrutibalasa.substack.com

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.

Thanks for reading CSS Simplified! Subscribe for free to receive new posts and support my work.

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.

Thanks for reading CSS Simplified! Subscribe for free to receive new posts and support my work.

2
Share this post

Do you know about the :empty selector in CSS?

shrutibalasa.substack.com
2 Comments
s m
Feb 4Liked by Shruti Balasa

excellent

Expand full comment
Reply
1 reply by Shruti Balasa
1 more comment…
TopNewCommunity

No posts

Ready for more?

© 2023 Shruti Balasa
Privacy ∙ Terms ∙ Collection notice
Start WritingGet the app
Substack is the home for great writing