0
0
CssHow-ToBeginner · 3 min read

How to Use :empty in CSS for Selecting Empty Elements

The :empty pseudo-class in CSS selects elements that have no children, including text nodes. Use it to style elements that are completely empty, for example, to highlight empty paragraphs or divs.
📐

Syntax

The :empty selector targets elements that have no child elements or text inside them. It matches only elements that are truly empty.

  • element:empty — selects empty elements of a specific type.
  • :empty — selects all empty elements regardless of type.
css
selector:empty {
  /* styles here */
}
💻

Example

This example shows how to style empty div elements with a red border and a message inside them using the :empty selector.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>:empty CSS Example</title>
<style>
  div:empty {
    border: 2px solid red;
    padding: 10px;
    background-color: #ffe6e6;
  }
</style>
</head>
<body>
  <div></div>
  <div>Not empty</div>
  <div> </div> <!-- This has a space, so not empty -->
  <div></div>
</body>
</html>
Output
You will see two <div> boxes with a red border and pink background because they are empty. The other divs with text or space inside have no border.
⚠️

Common Pitfalls

Many developers expect :empty to match elements with only whitespace, but it does not. Even a single space or newline inside an element means it is not empty.

Also, comments inside elements do not count as content, so elements with only comments are considered empty.

css
/* Wrong: This will NOT match because of the space */
div:empty {
  border: 2px solid blue;
}

/* Correct: No spaces or text inside */
div:empty {
  border: 2px solid green;
}
📊

Quick Reference

  • :empty matches elements with no children or text nodes.
  • Whitespace inside elements means they are NOT empty.
  • Comments inside elements do NOT count as content.
  • Use element:empty to target specific tags.

Key Takeaways

Use :empty to select elements with no child elements or text.
Whitespace inside an element means it is not empty and won’t match :empty.
Comments inside elements do not prevent :empty from matching.
Apply styles with :empty to highlight or handle empty containers.
Combine :empty with element selectors for precise targeting.