Course contentsShow
← Web Development
Lesson 453 of 2,9828. Advanced CSS Selectors and FeaturesFree lesson

:empty for Conditional Content Display

Target truly empty elements to hide containers, adjust layouts, or show placeholder content conditionally.

:empty for Conditional Content Display

You'll learn how to style elements differently when they contain absolutely nothing.

The Core Idea

The :empty pseudo-class selector targets elements that have zero content — no text, no child elements, not even whitespace. This lets you conditionally hide empty containers, adjust layouts when sections have no data, or display placeholder messages only when needed.

Think of it like a smart light switch that only turns on when a room is completely vacant — no furniture, no people, not even a speck of dust.

What Counts as Empty?

An element matches :empty only if it contains:

  • Nothing at all: <div></div>
  • Only HTML comments: <div><!-- comment --></div>

It does not match if there's:

  • Any text (even a space): <div> </div>
  • Any child elements: <div><span></span></div>

Practical Example

/* Hide empty containers completely */
.card-list:empty {
  display: none;
}

/* Show placeholder text when a section is empty */
.notifications:empty::before {
  content: "No new notifications";
  color: gray;
  font-style: italic;
}

/* Adjust layout when sidebar has no content */
.sidebar:empty {
  display: none;
}

.main-content:has(.sidebar:empty) {
  grid-column: 1 / -1; /* Full width when sidebar empty */
}

Common Use Cases

  • Hiding empty message containers so they don't create awkward spacing
  • Showing "no results" placeholder content dynamically
  • Adjusting grid layouts when optional sections have no data
  • Removing borders/padding from containers that should collapse when empty

Key Takeaway: Use :empty to conditionally style truly empty elements, creating cleaner layouts and more intelligent UI responses when content is absent.