Codectionary / Developer documentation / CSS

Selecting Empty Elements with :empty

:empty is useful for styling containers that contain no element children or non-empty text nodes under widely implemented behaviour.

What it is and why to use it

:empty is useful for styling containers that contain no element children or non-empty text nodes under widely implemented behaviour. It can make a deliberately empty slot visible while a populated slot keeps its ordinary appearance. Source whitespace matters, so an apparently blank container may not match.

Common mistakes and limitations

Selectors specifications have evolved around whitespace-only content, and deployed support must be checked. Do not assume a visually empty element always matches. Use real HTML text for an important empty-state message rather than relying solely on generated CSS content.

Try the example

The example pairs editable CSS with its own HTML preview. Run it, then change one declaration at a time and compare the result. Locally, put the CSS in a style element in the document head or in an external stylesheet linked from the HTML. Feature support varies by browser and version; use the linked reference and a useful fallback where needed.

HTML used by this example

<div class="slot"></div><div class="slot">A saved note</div><div class="slot"> </div>

Syntax

.slot:empty { ... }

Examples

Selecting Empty Elements with :empty

Run the CSS against the supplied HTML, then experiment with the values.

.slot { min-height: 2rem; border: 1px dashed #64748b; margin-block: .5rem; padding: .5rem; }
.slot:empty { background: #dbeafe; color: #172b4d; border-style: solid; }
  1. The first div has no content and matches :empty.
  2. The second has visible text, so it does not match.
  3. The third contains a space and is included to reveal implementation behaviour. This is useful for understanding why formatting whitespace can defeat an empty-state selector.
HTML used by this example
<div class="demo"><div class="slot"></div><div class="slot">A saved note</div><div class="slot"> </div></div>

Best practices

  • Selectors specifications have evolved around whitespace-only content, and deployed support must be checked. Do not assume a visually empty element always matches. Use real HTML text for an important empty-state message rather than relying solely on generated CSS content.
  • Inspect the relevant browser reference and test the browsers used by your audience.

Runtime & versions

Web browsers. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

CSS specifications (modules)

Specifications & further reading