Milind Daraniya

Unlocking the Power of the :empty CSS Pseudo-Class – Practical Use Cases

Published May 26th, 2023 16 min read

Hello web designers and developers! Today, let's dive into the often-overlooked CSS pseudo-class :empty and explore its practical and powerful use cases. The :empty pseudo-class allows us to target elements that have no children or are completely empty, giving us more control over styling and user experience. Let's uncover its potential with practical examples:

Example 1: Custom Empty State

HTML Structure:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>:empty CSS Pseudo-Class – Practical Use Cases</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <p>This paragraph has content.</p>
        <div class="empty-state">No content available.</div>
    </div>
</body>
</html>

CSS Styling:

/* styles.css */
.empty-state {
    display: none;
    color: #999;
    font-style: italic;
}

.container:empty .empty-state {
    display: block;
}

In this example, we use the :empty pseudo-class to display a custom empty state message when the .container element is empty. The .empty-state element is initially hidden with display: none, but when its parent .container is empty, the :empty pseudo-class will target it, and the message will become visible with display: block. This can be especially useful for displaying helpful messages when dynamic content is yet to be loaded.

Example 2: Removing Empty Anchor Tags

HTML Structure:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>:empty CSS Pseudo-Class – Practical Use Cases</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <nav>
        <a href="#">Home</a>
        <a href="#">About</a>
        <a href="#"></a>
        <a href="#">Contact</a>
    </nav>
</body>
</html>

CSS Styling:

/* styles.css */
nav a:empty {
    display: none;
}

In this example, we target empty anchor (<a>) tags within the <nav> element using the :empty pseudo-class and hide them with display: none. This can be beneficial for ensuring a clean and concise navigation menu by removing any empty or non-functional links.

By leveraging the :empty pseudo-class, we can enhance the user experience and manage empty elements more effectively with CSS.

Remember that the :empty pseudo-class targets elements with no children, including white spaces and line breaks. Use it wisely and combine it with other CSS selectors and properties to create even more dynamic and responsive designs.