Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Role of CSS :empty Selector
The CSS :empty selector targets elements that contain no children. An element is considered empty if it has no child elements, no text content, and no whitespace. This pseudo-class is useful for styling placeholder elements or removing unwanted margins from empty containers.
Syntax
selector:empty {
/* CSS properties */
}
What Counts as Empty
An element is considered empty if it contains:
- No child elements
- No text content
- No whitespace (spaces, tabs, line breaks)
Example: Styling Empty Paragraphs
The following example demonstrates how to apply different styles to empty and non-empty paragraph elements −
<!DOCTYPE html>
<html>
<head>
<style>
p {
width: 300px;
height: 20px;
background: gray;
margin: 10px 0;
padding: 10px;
}
p:empty {
width: 150px;
height: 20px;
background: orange;
border: 2px solid red;
}
</style>
</head>
<body>
<p>This paragraph has content.</p>
<p></p>
<p>Another paragraph with text.</p>
<p></p>
</body>
</html>
Four paragraphs appear: two gray paragraphs with text content (300px wide), and two orange paragraphs with red borders (150px wide) that are completely empty.
Example: Hiding Empty List Items
This example shows how to hide empty list items using the :empty selector −
<!DOCTYPE html>
<html>
<head>
<style>
li {
background: lightblue;
padding: 8px;
margin: 5px 0;
border-radius: 4px;
}
li:empty {
display: none;
}
</style>
</head>
<body>
<ul>
<li>Item 1</li>
<li></li>
<li>Item 3</li>
<li></li>
<li>Item 5</li>
</ul>
</body>
</html>
Only three list items are visible (Item 1, Item 3, Item 5) with light blue backgrounds. The empty list items are completely hidden from view.
Conclusion
The :empty selector is a powerful tool for targeting elements with no content. It's particularly useful for cleaning up layouts by hiding empty elements or providing visual feedback for placeholder content.
