DEV Community

Gökhan Taşkan
Gökhan Taşkan

Posted on • Updated on

Adding a TailwindCSS light-only variant in a few seconds using Vue 3 and VueUse

Just like you, we've got a sweet spot for Tailwind, adopting it in virtually every project. However, we stumbled upon a snag: the elusive light-only styles are conspicuously missing.

Now, before you get all flustered, there's a quick fix! We need to whip up a custom plugin in the tailwind.config file. Here's how you can get it done:

const plugin = require("tailwindcss/plugin");

/** @type {import('tailwindcss').Config} */
module.exports = {
  darkMode: "class",
  ...
  plugins: [
    plugin(({ addVariant }) => {
      addVariant("light", `.light &`);
    }),
  ],
};
Enter fullscreen mode Exit fullscreen mode

Simple, right? Moving on, let's put VueUse’s dark mode utility to good use and embellish our HTML with a class for the light mode:

<script setup lang="ts">
import { useDark, useToggle } from "@vueuse/core";

const isDark = useDark({
  selector: "html",
  attribute: "class",
  valueDark: "dark",
  valueLight: "light",
});

const toggleDark = useToggle(isDark);
</script>

<template>
  <button @click="toggleDark()">
    Switch Theme
  </button>
</template>
Enter fullscreen mode Exit fullscreen mode

In a nutshell, what we're doing here is assigning classes to the html tag based on the theme du jour - light or dark.

The next step is the fun part. Here's how you can put it to use:

<p class="light:text-gray-500">
  Paragraph...
</p>
Enter fullscreen mode Exit fullscreen mode

Now hold your horses, there's an important detail to remember: restart your dev server to ensure all these lovely changes have permeated your codebase.

For those of you who fancy going the extra mile, why not jazz up the browser's dark mode? Here's how:

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

@layer base {
  html.dark {
    color-scheme: dark;
  }
}
Enter fullscreen mode Exit fullscreen mode

Impressive, isn't it? Thanks for sticking with me on this ride! Stay curious, and happy coding!

Top comments (0)