tailwind-cssdaisyuidaisyui-5

How to define custom colours in DaisyUI that integrate with themes?


I am writing a card game based webapp with DaisyUI. I have an element which is a button that lets you cycle through suits:

A picture of a black club and a red diamond

Depending on the suit, the element can be either red or black. How can I make it so that the red is a colour that I can configure based on the theme (e.g. make it less saturated in the dark theme) without using primary/secondary/accent whose actual colour may not be red depending on the theme.

I tried to add a custom colour red to my custom theme but it did not recognize it as a class text-red:

@plugin "./daisy/daisyui-theme.js" {
  name: "mytheme";
  default: true;
  prefersdark: false;
  color-scheme: light;

  /* ... */

  --color-red: #ff3434;

  /* ... /*
}

Solution

  • Why are you configuring it in DaisyUI? Simply define the new color using the TailwindCSS @theme directive.

    @theme {
      --color-red: #ff3434;
    }
    

    Which you can later customize in different themes as follows:

    @custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));
    @custom-variant mytheme (&:where([data-theme=mytheme], [data-theme=mytheme] *));
    
    @theme {
      --color-red: #ff3434;
    }
    
    @layer theme {
      :root, :host {
        @variant dark {
          --color-red: #a32828;
        }
    
        @variant mytheme {
          --color-red: #cc0202;
        }
      }
    }
    

    Related:

    Working example:

    document.querySelector('button').addEventListener('click', () => {
      const html = document.documentElement;
      const current = html.getAttribute('data-theme');
    
      if (!current) {
        html.setAttribute('data-theme', 'dark');
      } else if (current === 'dark') {
        html.setAttribute('data-theme', 'mytheme');
      } else { 
        html.removeAttribute('data-theme');
      }
    });
    <script src="https://unpkg.com/@tailwindcss/browser"></script>
    <style type="text/tailwindcss">
    @custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));
    @custom-variant mytheme (&:where([data-theme=mytheme], [data-theme=mytheme] *));
    
    @theme {
      --color-red: #ff3434;
      --color-black: #555;
    }
    
    @layer theme {
      :root, :host {
        @variant dark {
          --color-red: #a32828;
          --color-black: #000;
        }
    
        @variant mytheme {
          --color-red: #02cc9d;
          --color-black: #929967;
        }
      }
    }
    </style>
    
    <button class="p-4 bg-sky-100 text-sky-800 cursor-pointer">Toggle theme: default/dark/mytheme</button>
    <span class="text-black">&#9824;</span> <!-- ♠ -->
    <span class="text-black">&#9827;</span> <!-- ♣ -->
    <span class="text-red">&#9829;</span> <!-- ♥ -->
    <span class="text-red">&#9830;</span> <!-- ♦ -->