Tony Messias

January 20, 2023

Hiding Empty States with CSS

This may be obvious to y'all, but I think it's still worth sharing. Whenever we're building a page, we need to think about its empty state. Sure, your list will look amazing with those icons, shades, typography, avatars... but what about when it's empty?

When doing server-side rendering in Blade I used to do something like:

<div id="chirps">
  @forelse($chirps as $chirp)
    @include('chirps._chirp', [
      'chirp' => $chirp,
    ])
  @empty
    <p id="empty-chirps">
      No chirps yet.
    </p>
  @endforelse
</div>

There are some downsides to this approach. I often had to cleanup these empty states whenever the list was being populated. Either the user created a resource or some other user did and everyone received it via broadcasting. For example, I always had to include a Turbo Stream to remove the empty state in broadcasts (see the new broadcasting chapter in the Turbo Laravel Bootcamp). Such a waste of bandwidth.

We can use the `:only-child` CSS pseudo-class to only display the empty state when the list is empty. Our Blade example would then become:

<div id="chirps">
  @each('chirps._chirp', $chirps, 'chirp')

  <div class="hidden only:block">
    <p>No chirps yet.</p>
  </div>
</div>

This uses the `only:` TailwindCSS pseudo-class modifier. No more having to remember to remove empty states when populating a list.

Screenshot from 2023-01-19 21-51-44.png


Enjoy.

About Tony Messias