Hiding Empty Elements with CSS

Hero image for Hiding Empty Elements with CSS. Image by Annie Spratt.
Hero image for '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 {  // styles in here will only be applied  // if the element is empty  display: none;}

:empty can be used on moreorless any CSS selector or element type (although originally intended for form elements such as textarea which has not yet been written in), and will only apply if the targeted element is absolutely and entirely empty. This definition is extremely strict: it will not match an element that contains whitespace (e.g.: a single space). It also will not match an element which has children, even if they themselves are empty.

For a more experimental approach, :mozonlywhitespace 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 :onlywhitespace, :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.


Categories:

  1. Accessibility
  2. CSS
  3. Development
  4. Front‑End Development
  5. Sass