CSS :empty Selector - Hide or Style Empty Elements

Use the CSS :empty pseudo-class to target elements with no children or text content. Hide empty containers, show placeholder messages, and handle dynamic content gracefully.

Structural Selectors

Detailed Explanation

The :empty Pseudo-class

The :empty selector matches elements that have no children — no child elements, no text nodes, not even whitespace (in most browsers).

Syntax

.container:empty {
  display: none;
}

What Counts as "Empty"?

Content Matches :empty?
No content at all Yes
Only HTML comments Yes
Whitespace (spaces/newlines) No (in CSS3) / Yes (in Selectors Level 4)
Child elements No
Text content No

Practical Use Cases

Hide empty containers:

.error-message:empty {
  display: none;
}

Show placeholder for empty state:

.results:empty::before {
  content: "No results found.";
  color: #999;
  font-style: italic;
  display: block;
  padding: 20px;
  text-align: center;
}

Remove spacing from empty elements:

.card-footer:empty {
  padding: 0;
  margin: 0;
  border: none;
}

Dynamic Content

The :empty selector works in real-time — if JavaScript adds content to an element, the styles are automatically removed:

// Element is initially :empty
const el = document.querySelector('.results');
// After adding content, :empty styles no longer apply
el.textContent = 'Found 5 items';

Specificity

:empty has specificity (0, 1, 0) — same as a class selector.

:blank (Future)

The proposed :blank pseudo-class would match elements that contain only whitespace, but it is not yet supported in any browser.

Use Case

The :empty selector is valuable for handling dynamic content where containers may or may not have content depending on application state. It is commonly used to hide empty error containers, show friendly empty-state messages in lists and search results, remove visual spacing from empty grid cells, and gracefully handle CMS content where optional fields may be blank.

Try It — CSS Selector Reference

Open full tool