The :empty selector in CSS is used to target elements that have no children. This can be useful for styling elements that are visually empty, such as empty lists or paragraphs.
Basic Usage
.empty-element:empty {
/* Styles for empty elements */
color: red;
font-weight: bold;
}
In this example, any element with the class empty-element that has no children will be styled with red text and bold font weight.
Practical Example: Styling Empty Lists
<ul class="my-list">
<li>Item 1</li>
<li>Item 2</li>
<li class="empty-item"></li>
</ul>
.my-list .empty-item:empty {
display: none;
}
In this case, the empty <li> with the class empty-item will be hidden, making the list appear more concise.
Key Points to Remember
- Specificity: The
:emptypseudo-class has a specificity of 1, which is relatively low. To ensure it overrides other styles, you may need to increase its specificity by adding additional selectors or using the!importantdeclaration (though this is generally discouraged). - Text Nodes: Elements with only text nodes are considered non-empty. To target truly empty elements, you might need to combine
:emptywith other selectors or JavaScript. - Browser Compatibility:
:emptyis widely supported across modern browsers. For older browsers, consider using a JavaScript-based solution or a CSS fallback.