Skip to main content

CSS :empty pseudo class

When building a user interface, it is common to have a container element that conditionally contains content. A simple example is an element that displays error information when a form field is invalid. To accomplish this, you have two options:

  1. Always render the container in the DOM and conditionally add children (e.g. text, other nodes)
  2. Conditionally render the container when needed.

There are use cases for both approaches. When working with vanilla JavaScript, I typically reach for the former. If I were building the interface with a front-end library, then I use the later.

A problem that arises with option 1 is spacing in between elements. If you are using flex box or grid with a gap the empty element will be included in the layout and will result in a double space between visible elements.

See the Pen Removing extra flex/grid spacing with :empty by Sean McPherson (@SeanMcP) on CodePen.

The solution is to use the :empty pseudo class to select the empty element and hide it with display: none. Once the element is removed from the flex/grid, the gap between elements are consistent.

It is worth noting that the double spacing is not an issue with patterns like Every Layout’s stack, which uses the browser’s collapsing margins. But if you are using flexbox or grid, then the problem will eventually arise.

About the author

Sean McPherson is a software engineer for Khan Academy who specializes in web development. He lives with his wife, sons, and dog in Pittsburgh, PA.