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.
Related articles
- Making Links Easy to Recognize
Make links recognisable with underlines, clear focus states, useful text, and behaviour that does not surprise the reader.
- When CSS Layout Order Stops Matching the HTML
Keep Grid and Flexbox layouts aligned with the HTML order so keyboard focus and screen reader reading do not jump around the page.
- Keyboard Focus Styles With :focus-visible
Keep a clear keyboard focus indicator while avoiding the same focus ring after every pointer interaction.