john_ryan
john_ryan

Reputation: 1787

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

Upvotes: 28

Views: 22505

Answers (2)

sadeq shahmoradi
sadeq shahmoradi

Reputation: 2365

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 change automatically

Upvotes: 45

Rifky Niyas
Rifky Niyas

Reputation: 2046

One trick that you can make use of is by extracting as components.

In your tailwind stylesheet

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
  .red-bg {
    @apply bg-red-100 dark:bg-red-dark-100;
  }
}

Then you can use it as

<div class="red-bg"></div>

and it work as intended. However, it would be a best practice to use other approaches in re-using the styles since it would be inconvenient to extend this trick to all colors used in your project.

Upvotes: 1

Related Questions