CSS :empty Selector
The selector :empty is a pseudo-class in CSS selecting elements that have no children. In simple words, this selector targets the elements that define no children.
The general syntax to define :empty selector in CSS is as follows:
element:empty {
/* CSS properties */
}In the above syntax,
element: It represents the type of element that you want to target.:empty: This is the pseudo-class selector that selects elements with no content, including text nodes such as white space, actual text.
The selector will not match an element that contains:
- Text (including whitespace).
- Comments.
- Child elements.
Example of an Empty Element:
<div class="empty"></div>In this example, the <div> element is empty and would be selected by the :empty selector.
Example of a Non-Empty Element:
<div class="not-empty"> </div>In this example, the <div> element contains a whitespace character, which will be considered as not empty.
Examples of CSS :empty Selector
Let’s take an example in which we have multiple paragraphs on our webpage, and we want to hide the ones that are empty.
Example 1:
<!DOCTYPE html>
<html>
<head>
<style>
p:empty {
display: none;
}
</style>
</head>
<body>
<p class="filled">This is a filled paragraph.</p>
<p class="empty"></p>
<p class="empty"></p>
</body>
</html>
In this example, the selector p:empty will select all empty <p> elements and hide them from the page. Only the filled paragraph will remain visible on the webpage.
Let’s take another example in which we will use the CSS :empty selector to add a different background color to empty elements.
Example 2:
<!DOCTYPE html>
<html>
<head>
<style>
div.content:empty {
background-color: #f0f0f0;
border: 1px dashed #ccc;
}
</style>
</head>
<body>
<div class="container">
<div class="content"></div>
<div class="content">Not empty</div>
</div>
</body>
</html>
In this example, the div.content:empty selector will select the empty <div> element within the parent div element with class attribute value “.container”. It will style a light gray background and a dashed border.
Let’s take an example in which we will have a list where some items will be empty, and we will hide the empty items using the CSS :empty selector.
Example 3:
<!DOCTYPE html>
<html>
<head>
<style>
li:empty {
display: none;
}
</style>
</head>
<body>
<ul>
<li>Item 1</li>
<li></li>
<li>Item 3</li>
<li></li>
</ul>
</body>
</html>
In this example code, the empty <li> elements will be hidden, and left only the list items that have content.
Key Points to Remember
There are the following key points that you should keep in mind before using :empty selector provided by CSS. They are as:
- The CSS :empty selector targets those elements that have no children, including text nodes or elements.
- Elements containing whitespace, comments, or child nodes are not considered empty.
- Use the :empty selector to hide, style, or manipulate empty elements dynamically.









