DEV Community

Cover image for Unveiling the Power of the :empty() CSS Pseudo-Class
Matt Miller
Matt Miller

Posted on

Unveiling the Power of the :empty() CSS Pseudo-Class

In the realm of CSS selectors, the :empty pseudo-class stands out as a formidable tool for targeting elements devoid of any children. Whether you're seeking to style empty containers differently or apply dynamic effects based on content presence, :empty proves to be a versatile and valuable asset in your styling arsenal.

The syntax for utilizing the :empty pseudo-class is elegantly simple:

:empty {
  /* CSS rules */
Enter fullscreen mode Exit fullscreen mode

This pseudo-class selects elements that have no children, regardless of whether those children are element nodes or text content (including whitespace).

Let's delve into a couple of examples to grasp the practical application of the :empty pseudo-class:

<div class="box"><!-- I will be lime. --></div>
<div class="box">I will be pink.</div>
<div class="box">
  <!-- I will be pink in older browsers because of the whitespace around this comment. -->
<div class="box">
    <!-- I will be pink in all browsers because of the non-collapsible whitespace and elements around this comment. -->
Enter fullscreen mode Exit fullscreen mode
.box {
  background: pink;
  height: 80px;
  width: 80px;

.box:empty {
  background: lime;
Enter fullscreen mode Exit fullscreen mode

In this example, the boxes with no visible content will be styled with a lime background, while those with content will retain the pink background.

Accessibility Concerns:
It's crucial to consider accessibility implications when utilizing the :empty pseudo-class. Assistive technologies like screen readers rely on accessible names to parse interactive content accurately. Therefore, ensuring that interactive elements have an accessible name is paramount for accessibility compliance.

Combined instance with :not()

section:not(:empty) {
    background: red;
    padding: 1rem;

section:empty {
  display: none;
Enter fullscreen mode Exit fullscreen mode

The :empty pseudo-class empowers CSS developers with the ability to target elements lacking content dynamically. By understanding its syntax, applications, and accessibility considerations, you can wield this pseudo-class effectively to enhance both the aesthetics and accessibility of your web projects. Incorporate the :empty pseudo-class into your CSS toolkit to unlock new possibilities in styling and user experience design.

Top comments (0)