Hiding Empty Elements with CSS

Abstract image used to represent Hiding Empty Elements with CSS
Image by Annie Spratt.

A very quick tip: the :empty CSS pseudoclass is simple, easy to understand and (now) incredibly wellsupported. So, to hide an empty element, it is as simple as:

.classname:empty {
  /* Apply these styles only when the element is empty. */
  display: none;
}

:empty matches an element with no element children or nonempty text nodes. In current browsers, even a single space prevents a match; an empty child element also prevents it. Comments do not count. This checks the document's child nodes, not the current value a user has typed into a form control.

For a more experimental approach, :-moz-only-whitespace will match any element which contains either nothing, or only whitespace. Unsurprisingly, however, support is limited to Firefox for the time being.

Whilst there is currently some discussion about how :only-whitespace, :blank, and :empty might be defined in Selectors Level 4, at the time of writing nothing has yet been formally agreed or implemented by any of the browser vendors. It seems likely that eventually :empty will incorporate elements that contain whitespace too.

Postscript

July 2026: Selectors Level 4 now defines :empty as ignoring document whitespace, but MDN notes that current browsers still implement the older, stricter behaviour described here. The specification also repurposed :blank for empty user input, and browser implementation remains incomplete.

Want to find out more?

If you need senior handson support with a complex React or Next.js platform, migration, performance issue, or technical SEO problem, send me the context and I'll tell you where I can help.