DEV Community

CSS :empty Selector

Samantha Ming on August 05, 2019

Often, we want to style elements that contain content. How about when an element has no children or text at all? Easy, you can use the :empty sel...
Collapse
 
link2twenty profile image
Andrew Bone

I love seeing little known features like this getting some spotlight! It's probably worth noting when the level 4 selectors roll out white space will be included as empty 🙂.

The :empty pseudo-class represents an element that has no children except, optionally, document white space characters.

drafts.csswg.org/selectors-4/#the-...

Collapse
 
samanthaming profile image
Samantha Ming

Oh crazy! That’s a game changer! Let me add that to my notes, thank you for sharing 😊👏👏

Collapse
 
okumurakengo profile image
奥村健吾 • Edited

I did not know. Thank you very much !

also :not and :empty can be used to hide empty state 😀

<style>
.alert:not(:empty) {
  background: pink;
  padding: 10px;
}
</style>
<div class="alert"></div>
<div class="alert">Alert Message</div>

Thanks!
 

Collapse
 
samanthaming profile image
Samantha Ming

Nice! that's an awesome application of it 👍

Collapse
 
jlabs profile image
jlabs • Edited

I've used this recently within ul that show's a message when the ul has no children - the list was populated via JS.

Collapse
 
samanthaming profile image
Samantha Ming

It use to be that designers would had to hand this back to developers to fix this JS. Now we're empowering designers to make these fixes with just CSS. Pretty neat! (but JS developers should probably fix these empty population of these elements 😅)

Collapse
 
madebyhector profile image
Hector Osborne Rodriguez

I have forgotten about this because the browser support wasn’t ready a few years back. Glad to hear that it is making improving.

Collapse
 
samanthaming profile image
Samantha Ming

Support definitely has improved! And I'm happy that it did 👍

Collapse
 
kayla profile image
Kayla Sween

I wasn't really aware there was a :empty pseudo-class, but I never went looking for it either.😅 I can think of a few instances in my applications where this will come in handy! Thanks for sharing!

Collapse
 
samanthaming profile image
Samantha Ming

YES! you're very welcome! and don't hesitate to jump back here to share with us your use-case, always cool to see how others apply this 😊