1 min read

CSS :empty Pseudo-class

The :empty pseudo-class represents any element that has no children. Children can be either element nodes or text (including whitespace).

1. What counts as "Empty"?

An element is considered empty if it contains nothing between its opening and closing tags.

  • Empty: <div></div>
  • Empty: <div><!-- This is a comment --></div> (Comments are ignored)
  • Not Empty: <div> </div> (Whitespace is a text node)
  • Not Empty: <div><span></span></div> (Contains an element)
  • Not Empty: <div>Hello</div> (Contains text)

2. Basic Usage

This is particularly useful for hiding containers that are dynamically populated but look ugly when empty (e.g., having a border or padding).

.alert {
  background: <a href='/?search=%23ffcccc' class='obsidian-tag'>#ffcccc</a>;
  border: 1px solid red;
  padding: 10px;
}

/* Hide the alert if it has no content */
.alert:empty {
  display: none;
}

3. The Whitespace Issue

A common pitfall is that whitespace (spaces, tabs, line breaks) counts as content.

<!-- This is NOT :empty because of the line break -->
<div class="box">
</div>

If your HTML formatter adds line breaks or indentation inside elements, :empty will not match.

4. :not(:empty)

Conversely, you can style an element only if it does have content.

/* Only apply padding if there is content inside */
.notification:not(:empty) {
  padding: 1rem;
  border: 1px solid <a href='/?search=%23ccc' class='obsidian-tag'>#ccc</a>;
}

programming/css/css programming/css/pseudo-classes-and-pseudo-elements programming/css/selectors