TailwindCSS: How to do a light mode only modification?

943 Views Asked by At

I would like to do a light mode only modification of a style.

Unfortunately, it doesn't seem like light: exists.

I know that the default approach is to style the light styles and then override in dark mode.

However, my styles come from a library, so in order to achieve the override I want, I'd have to read the source code of the styling library, and then manually set the dark: value to what it was. Something like light: would make the code much cleaner.

Is there anything like it?

I tried Google, looking for SO and the Tailwind docs, but couldn't find anything like it.

I also couldn't find an "inversion" modifier (e.g. non:dark:).

2

There are 2 best solutions below

0
Cornel Raiu On BEST ANSWER

I played a bit with it and was able to add a light: variant by looking at this repo

The tailwind.config looks like this:

const { themeVariants, prefersLight, prefersDark } = require("tailwindcss-theme-variants");

/** @type {import('tailwindcss').Config} */
export default {
  theme: {
    // ...
  },
  plugins: [
    themeVariants({
      themes: {
        light: {
          mediaQuery: prefersLight /* "@media (prefers-color-scheme: light)" */,
        },
        dark: {
          mediaQuery: prefersDark /* "@media (prefers-color-scheme: dark)" */,
        },
      },
    }),
  ],
}

And then, in the HTML I am able to use dark: and light: modifiers like here:

<div class="dark:bg-black light:bg-red-300 py-6">

...

</div>

Here is a Play Tailwind where you can see it in action

If the library you use relies on a class on the html tag for switching between light and dark, according to the same repo, you may use the config to look for that particular class name instead:

const { themeVariants } = require("tailwindcss-theme-variants");

/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    // ...
  },

  plugins: [
    themeVariants({
      themes: {
        light: {
          selector: ".light-theme",
        },
        dark: {
          selector: ".dark-theme",
        },
      },
    }),
  ],
};

This will generate CSS like:

:root.light-theme .light\:bg-red-300{
  --tw-bg-opacity: 1;
  background-color: rgb(252 165 165 / var(--tw-bg-opacity))
}

I hope that works for you. I never did this in a large scale app, and I am not sure what the limitations would be for this solution, but it seems to be working on this simple example.

0
ADITYA On

If your styles come from a library and you don't want to manually override in dark mode, one option could be to create a utility class or a separate set of styles specifically for dark mode.

<div class="bg-white text-black">
  <!-- Content -->
</div>
<div class="dark:bg-gray-800 dark:text-white">
  <!-- Content -->
</div>