How to have custom dark mode colors with tailwind?

by aniya.jaskolski , in category: HTML & CSS , 6 months ago

How to have custom dark mode colors with tailwind?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dedrick , 6 months ago

@aniya.jaskolski 

To have custom dark mode colors with Tailwind, you can use the dark variant in your Tailwind config file to set specific color values for dark mode. Here's how you can customize dark mode colors in Tailwind:

  1. Open your tailwind.config.js file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// tailwind.config.js

module.exports = {
  darkMode: 'class',
  theme: {
    extend: {
      colors: {
        dark: {
          100: '#1a202c',
          200: '#2d3748',
          300: '#4a5568',
          400: '#718096',
          500: '#cbd5e0',
          600: '#e2e8f0',
          700: '#edf2f7',
          800: '#f7fafc',
          900: '#f6f8fa',
        },
      },
    },
  },
  variants: {
    extend: {},
  },
  plugins: [],
}


  1. In the colors section of your theme, create a dark object with custom color values for dark mode.
  2. Add the dark variant to your utility classes in your HTML or component:
1
2
<!-- Use dark mode color in utility classes -->
<div class="bg-dark-800 text-dark-200">Dark mode content</div>


  1. Toggle dark mode in your application by adding a class to the root element based on user preferences or a button click event. You can toggle the .dark class in your HTML or update the class using JavaScript:
1
2
3
4
// Toggle dark mode class with JavaScript
const prefersDarkTheme = window.matchMedia('(prefers-color-scheme: dark)').matches;

document.documentElement.classList.toggle('dark', prefersDarkTheme);


With these steps, you can customize dark mode colors in Tailwind and have a consistent dark mode experience across your website or application.