CSS :empty Pseudo Class

CSS :empty Pseudo Class

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

div:empty { background-color: lightgray; border: 1px dashed #ccc; height: 50px; width: 100px; }

✅ Targets empty <div> elements and gives them a visible dashed border.

2. Example – Styling Empty Elements

<div class="box"></div> <div class="box">Content inside</div>
.box { width: 200px; height: 50px; border: 2px solid black; margin: 10px; } .box:empty { background-color: lightblue; border: 2px dashed red; }

✅ 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!

<div class="box"> </div> <!-- Not considered empty due to the space -->

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

<ul> <li>Item 1</li> <li></li> <!-- Empty --> <li>Item 3</li> </ul>
li:empty { display: none; }

✅ 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.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close