|

Using the CSS :empty Selector

Using the CSS :empty Selector Photo by Isabela Kronemberger on Unsplash

CSS :empty Selector

We often need to apply styles to elements that contain content. But what should we do when an element has no content or children? That’s where the :empty selector comes in! 🎨

<div>hey</div>
<!-- NOT empty: contains text -->

<div> </div>
<!-- NOT empty: contains a whitespace character -->

<div></div>
<!-- YES, empty: nothing inside -->
!

These gray blocks above were generated using the following HTML and CSS setup:

<div class="our-div">!</div>
<div class="our-div"></div>
.our-div {
  margin: 16px 0;
  padding: 16px;
  background: gainsboro;
}

.our-div:empty {
  background: gray;
}

What is considered empty?

An important detail about :empty is understanding what it actually considers as an empty element. Let’s refer to the definition provided by MDN:

The CSS pseudo-class :empty represents any element that has no children. Here, children can be other elements or text nodes (including whitespace characters). Comments and processing instructions are not considered when determining whether an element is empty.

✅ Considered empty

If an element does not contain any whitespace or any other child elements, it is recognized as empty.

<p></p>

Even if there is a comment inside the element, it will still be treated as empty, as long as there are no spaces or line breaks:

<p><!-- comment --></p>

❌ Not empty

If there is any whitespace inside the element, it will not be considered empty. This includes simple spaces or line breaks.

If the element contains another element inside it, it will also not be considered empty.

<p> </p>

<p>
  <!-- comment -->
</p>

<p><span></span></p>

Practical :empty examples: error messages

We can use :empty to display an error icon in a given element only when the element is empty.

Invalid email
<!-- No error message -->
<div class="our-div-error"></div>

<!-- With error message -->
<div class="our-div-error">Invalid email</div>
.our-div-error:before {
  content: '❌';
}

.our-div-error:empty:before {
  content: 'Error: ';
}

Browser support

The :empty selector is widely supported, working across all modern browsers, including jurassic versions 🦕 like Internet Explorer 9. I hope this article was helpful to you! See you next time ✌️