Search code examples
tailwind-css

Tailwind colors based on dark mode


Is there any way to define different colors in the tailwind config so that the dark mode are applied without the dark selector?

Currently I have an object like:

const colors = {
 light: {
    red: {
     100: "#880808",
    ...
    }
  },
 dark: {
    red: {
     100: "red",
    ...
    }
  },

} 

I'd like to just use red-100 and have the color be mapped automatically (just via bg-red-100) without having to specify bg-red-100 dark:bg-red-dark-100


Solution

  • You can define your colors in your CSS file like this :

    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    
    @layer base {
    
      :root {
        --color-primary: 247 147 34;
        --color-text: 33 33 33;
        --color-success: 0 200 81;
        --color-info: 51 181 229;
        --color-warn: 255 187 51;
        --color-error: 254 78 78;
      }
    
      :root[class~="dark"] {
        --color-primary: 247 147 34;
        --color-text: 33 33 33;
        --color-success: 0 200 81;
        --color-info: 51 181 229;
        --color-warn: 255 187 51;
        --color-error: 254 78 78;
      }
    }
    

    and then use this config in your tailwind.config.js:

    /** @type {import('tailwindcss').Config} */
    module.exports = {
      darkMode: "class",
      theme: {
        colors: {
          primary: "rgb(var(--color-primary) / <alpha-value>)",
          text: "rgb(var(--color-text) / <alpha-value>)",
          success: "rgb(var(--color-success) / <alpha-value>)",
          info: "rgb(var(--color-info) / <alpha-value>)",
          warn: "rgb(var(--color-warn) / <alpha-value>)",
          error: "rgb(var(--color-error) / <alpha-value>)",
          transparent: "transparent",
          current: "currentColor",
        },
    }
    

    now if you set the dark class on your document root colors changed automatically