What is the :empty pseudo-class in CSS?

The :empty pseudo-class selects the selector element with no elements or text node (including whitespace).

Syntax

selector:empty{
  background-color: pink;
}

Example for empty elements

Here are some of the cases where an element is considered empty:

  • No content between element tags
<p></p>
  • Only comments between the element tag
<p><!-- I'm an empty element. --></p>

Example for non-empty elements

Here are some of the cases where an element is considered empty:

  • Having any text node or element node inside the element
<p>Non-empty</p>

<p>
  <span> non-empty</span>
</p>
  • Having a space between the tags
<p>  </p>
<p>
  <!-- The white space(new line and tab space) around this comment makes its parent as a "non-empty" element -->
</p>

In the above code, we have set a pink background for empty blocks and a deeppink background for non-empty blocks using the :empty pseudo-class.

Free Resources