The :empty pseudo-class
Published on
We can use the :empty
pseudo-class as a way to style elements on your webpage that are empty.
You might wonder why you’d want to style something that’s empty. Let’s say you’re creating a todo list.
You want to put your todo items in a list, but what about when you don’t have any items in your list yet?
That’s where :empty
can help.
ul.todo-list:empty {
display: none; /* The list won't be rendered on the page */
}
There is a bit of a catch - :empty is pretty strict about what it considers “empty.” Even a single space or line break will make it so your element is no longer empty. For example:
<div></div>
<!-- This is empty! -->
<div> </div>
<!-- Not empty (has a space) -->
<div><!--comment--></div>
<!-- Still empty! Comments don't count -->
The spec has been updated so those examples should all count as empty, but so far, no browsers have implemented this yet.
It’s particularly handy for data-driven layouts where you might have optional content. Like if you’re displaying user profiles and some fields might be blank, you can use :empty
to handle those cases gracefully instead of showing empty boxes everywhere.
Dive deeper
-
Tobias Ahlin Bjrorrome has a nice article on the topic that also explores using it with
:has()
. -
In this video I look at using
:empty
, as well as:target
and:only-child
.