CSS :empty
Pseudo-Class
The :empty
pseudo-class selects elements that contain no children, including text nodes. It is useful for detecting and styling empty elements, such as <div>
, <p>
, or <li>
.
1. Syntax
✅ Targets empty <div>
elements and gives them a visible dashed border.
2. Example – Styling Empty Elements
✅ The empty div gets a light blue background and a red dashed border.
✅ The div with content remains unchanged.
3. Important Notes on :empty
🚨 Whitespace (Spaces, Newlines, Tabs) Counts as Content!
❌ This is NOT empty because of the space inside.
✅ Use .trim()
in JavaScript to check if an element is visually empty.
4. Use Case – Hiding Empty List Items
✅ Removes empty <li>
elements to keep lists clean.
5. :empty
vs :blank
(Upcoming)
🔹 :empty
→ Matches elements with no children at all (no spaces).
🔹 :blank
→ Future pseudo-class that will match empty or whitespace-only elements.
6. Browser Support
✅ Fully supported in Chrome, Edge, Firefox, Safari, and Opera.
✅ Works on any HTML element that can be empty.
7. Best Practices
✔ Use :empty
to highlight missing content dynamically.
✔ Combine with display: none;
to remove unnecessary elements.
✔ Ensure no unintended whitespace breaks the rule.