Search code examples
cssreactjstailwind-css

How to create custom Tailwind colors based on media-query?


How would I change the entire Tailwind color scheme based on the users preferences. Is this even possible or do I have to add "dark:" before every class?

Here is my current tailwind.config.js:

module.exports = {
    purge: ["./src/**/*.jsx"],
    theme: {
        themeVariants: [],
        variants: {},
        extend: {
            colors: {
                main: {
                    100: "#ECEFF4",
                    200: "#E5E9F0",
                    300: "#D8DEE9",
                    400: "#4C566A",
                    500: "#434C5E",
                    600: "#3B4252",
                    700: "#2E3440",
                    800: "#292E39",
                    900: "#000510",
                },
            },
        },

    },
};

This is approximately what I would like:

extend: {
    colors: {
        if(lightmode)
        {
            main: {
                100: "#ffffff",
                200: "#ffffff",
                300: "#ffffff",
                400: "#ffffff",
                500: "#ffffff",
                600: "#ffffff",
                700: "#ffffff",
                800: "#ffffff",
                900: "#ffffff",
            },
        }
        if(darkmode)
        {
            main: {
                100: "#ECEFF4",
                200: "#E5E9F0",
                300: "#D8DEE9",
                400: "#4C566A",
                500: "#434C5E",
                600: "#3B4252",
                700: "#2E3440",
                800: "#292E39",
                900: "#000510",
            },
        }
    },
},

Solution

  • Why are you making it so difficult? Tailwind has a darkmode class utility.

    When you add the dark mode class to the HTML attribute you can specify a different color.

        <!-- Dark mode not enabled -->
    <html>
    <body>
      <!-- Will be white -->
      <div class="bg-white dark:bg-black">
        <!-- ... -->
      </div>
    </body>
    </html>
    
    <!-- Dark mode enabled -->
    <html class="dark">
    <body>
      <!-- Will be black -->
      <div class="bg-white dark:bg-black">
        <!-- ... -->
      </div>
    </body>
    </html>
    

    https://tailwindcss.com/docs/dark-mode

    When you do these types of things try and stick with the flow of the framework. It will help greatly remove headaches when they update and you have to refactor code.

    If you work hacky like this it will only hurt you in the future.