Ronalds Vilciņš

Selecting empty elements with CSS :empty

CSS has a selector for elements with no content: :empty. It matches an element only when there are no child elements and no text nodes inside it.

div:empty {
  background-color: lightgray;
  border: 1px solid gray;
  height: 50px;
  width: 50px;
}

This styles every empty div. You can narrow it to a particular part of the page by combining it with another selector:

.container :empty {
  background-color: lightgray;
  border: 1px solid gray;
  height: 50px;
  width: 50px;
}

The easy detail to miss is whitespace. An element containing a space or line break has a text node, so it is not considered empty. If :empty appears not to work, check the markup before blaming the CSS.

Enjoyed reading this?

If you found this article helpful, consider supporting my writing. Every little bit helps keep this blog going.

← Back to all articles