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
.