Use CSS’ `only-child` instead of `if/else` logic

use-css’-`only-child`-instead-of-`if/else`-logic

This article was originally published on Rails Designer

Rails developers are spoiled when talking about not needing to write code. Lots of the tedious things are done for you. Hotwire leveled up the amount of custom JavaScript that is not needed (to be written).

But CSS has become really powerful to over the past years. Whenever I can I try to use CSS to do the logic for me.

One of those situations is empty states. For example, a messages inbox:

Image description

The HTML looks something like this:

 class="divide-y divide-gray-100">
  
  • Now previously you might solve this with a if/else statement:

     class="divide-y divide-gray-100">
        
  • <⁠% if @messages.none? %>
  • class="text-base font-normal leading-tight text-center text-gray-400"> No messages yet

  • <⁠% end %>

    But with the only-child pseudo-class (I am using Tailwind CSS’ only utility class here, you can write it like so:

     class="divide-y divide-gray-100">
      
  • class="hidden only:flex"> class="text-base font-normal leading-tight text-center text-gray-400"> No messages yet

    Here the (wrapping) li-element is hidden (display: none;) by default and only(!) if it’s the only element display it (eg. display: flex).

    One big upside of this solution, is that if you remove the messages via Turbo Streams, the “logic” is automatically applied without needing to update the complete list (ul-element) for the logic to kick in.

    Pretty cool, right?

    This is the first article in a collection of Selector Logic

    Total
    0
    Shares
    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Previous Post
    scaling-product-organizations:-a-strategic-blueprint-for-sustainable-growth

    Scaling product organizations: A strategic blueprint for sustainable growth

    Next Post
    10-essential-tips-for-data-driven-content-marketing-[sponsored]

    10 Essential Tips for Data-Driven Content Marketing [Sponsored]

    Related Posts
    c++-指向類別成員的指位器的實作細節

    C++ 指向類別成員的指位器的實作細節

    C++ 可以定義指向成員函式的指位器, 不過因為成員函式可能是虛擬函式, 如何能夠透過指向成員函式的指位器達到呼叫正確的成員函式呢?本來就來簡單探究。(本文均以 g++ 為例, 並且只探討單純的單一繼承)。 指向非虛擬函式的指位器 首先來看個簡單的範例, 建立指向非虛擬函式的指位器: #include using namespace std; class A { public:…
    Read More