The :empty
pseudo-class targets elements that have no children, including text nodes. This is useful for hiding or styling empty elements that might otherwise take up space or look broken.
Example 1: Hiding Empty Paragraphs
/* Selects any <p> element with no content */
p:empty {
display: none;
}
Explanation
This CSS rule finds any paragraph (<p>
) that is completely empty and hides it, preventing empty paragraphs from creating unwanted vertical space.
Example 2: Styling Empty Divs
/* Adds a visual indicator to empty <div> elements */
div:empty {
border: 1px dashed #ccc;
min-height: 20px;
}
Explanation
This code applies a dashed border and a minimum height to any empty <div>
, which can be helpful during development to identify empty containers.
Example 3: Hiding Empty Table Cells
/* Selects any empty <td> or <th> element */
td:empty, th:empty {
background-color: #f2f2f2;
}
Explanation
This CSS gives a light grey background to any table cell (<td>
or <th>
) that is empty, making it clear which cells have no data.
Example 4: Alert for Empty Fields
/* Adds a message to an empty alert box */
.alert:empty::before {
content: "This alert is empty.";
color: #999;
}
Explanation
This rule uses the ::before
pseudo-element to insert a text message into any element with the class .alert
that is empty.
Example 5: Styling Empty Spans
/* Styles empty <span> elements used as icons */
span.icon:empty {
display: inline-block;
width: 16px;
height: 16px;
background-color: #007bff;
}
Explanation
This CSS targets empty <span>
elements with the class .icon
and styles them as colored blocks, a common technique for creating simple CSS icons.