Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

:empty — selecting empty elements

The :empty pseudo-class tests an element’s structure, not its appearance. Comments do not prevent matching, but child elements or text can. For whitespace, distinguish the rules in Selectors Level 3 from the Level 4 draft.

Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required

Syntax

:empty

:empty is a structural pseudo-class without arguments. .box:empty selects elements with class .box that satisfy the empty-content condition. Comments and processing instructions do not affect that condition.

Any child element prevents matching, even if that child is itself empty. Nonzero-length text also matters. Emptiness concerns the document tree, not whether the content is visible.

Whitespace introduces an important distinction: in Selectors Level 3, even a lone space or newline prevents matching. The Selectors Level 4 draft allows document whitespace. Do not assume support for this change without checking the target browser. A nonbreaking space U+00A0 is not covered by that exception.

The example deliberately avoids the case affected by this difference. a has no children, and b contains only a comment; both match. c contains text, and d contains a child element, so neither matches. The expected output is a, b.

Examples

<!doctype html>
<meta charset="utf-8">
<title>:empty</title>
<style>
  .box { min-height: 24px; margin: 4px; border: 2px solid gray; }
  .box:empty { border-color: green; }
</style>
<div class="box" id="a"></div>
<div class="box" id="b"><!-- comment --></div>
<div class="box" id="c">text</div>
<div class="box" id="d"><span></span></div>
<pre id="result"></pre>
<script>
  const ids = [...document.querySelectorAll('.box:empty')]
    .map(element => element.id);
  document.getElementById('result').textContent = ids.join(', ');
</script>

Result

a, b

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources