Power of :empty

Zoran Perin
3 min readMar 10, 2017

--

CSS is a peculiar creature. You may work with it for years and yet not touch many things hidden under it’s hood. I recently came to a very simple but usefull pseudo selector that really could help you out.

The :empty pseudo selector selects elements that are empty. Saying that I mean empty like really empty, no string, no HTML, not even spaces!

Power of this pseudo selector lies in fact that many times you don’t want to show some element if you don’t have nothing to show. Here’s and example: imagine that you have a page with articles feed, for example your news landing page. Some of article could have tag that will be visualy represented as red square with tag name. That tag will have padding and background-color that will be present even if text (tag) is not present.

Usual way of doing this would be to check with server side or client side script if tag is present and if it is, element with content will be printed out. This is where :empty could help you!

.tag {
background-color: red;
color: #fff;
padding: 5px 10px;
}
.tag:empty {
display: none;
}

And that’s it! No logic to be performed, no query. Boom!

Support

If you visit the amazing http://caniuse.com and check this selector you will find out that it is adopted in every modern browser (even stinky IE9 supports it!).

But…

Why I don’t use it that much? The :empty pseudo selector has nasty habit that demands not to have anything inside element you want to target. I realy mean NOTHING: nada, ništa, nichts, rien, nic. So, being nice developer and paying attention to your code (indentation, spacing, the way you format it) will add some spaces (tabs) to elements so this handy selector will fail shortly. In other words, if you write code like this, it won’t work:

<div class=”tag”>
</div>

In order to have it working, you will need to have inlined with no spaces, like this:

<div class=”tag”></div>

Conclusion

Even if this pseudo selector is powerful and deigned to solve much bigger issues than it seems, it usualy fails to do that because it counts empty space inside element as something, so it cannot perform the task.

I’d say that this may be handy but you really need to take care of how you write the code and that’s actually the part I dislike the most: I don’t want code to be interpreted after the way it is written. That’s why CSS and HTML are so good and this pseudo selector is potentialy dangerous because you can simply forget this fact while writting.

--

--

Zoran Perin

Front-end Web Developer. Firm on Sass, JS and 6-strings. Wannabe nihilist. https://zoranperin.com/