Home Web Front-end CSS Tutorial Applying Dark Mode in Next.js using CSS Variables

Applying Dark Mode in Next.js using CSS Variables

Aug 10, 2024 pm 08:37 PM

In today’s web development landscape, offering a dark mode option has become almost essential for a modern user interface. In this article, we’ll explore how to implement a robust dark mode solution in a Next.js project using CSS variables, Tailwind CSS, and some helpful tools and packages.

Tailwind CSS for Utility Classes

First, let’s set up Tailwind CSS in our Next.js project. Tailwind provides a utility-first approach to styling, which can significantly speed up our development process.

To install Tailwind CSS, run the following commands in your project directory:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Copy after login

Then, configure your tailwind.config.js file:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./app/**/*.{js,ts,jsx,tsx,mdx}",
    "./pages/**/*.{js,ts,jsx,tsx,mdx}",
    "./components/**/*.{js,ts,jsx,tsx,mdx}",

    // Or if using `src` directory:
    "./src/**/*.{js,ts,jsx,tsx,mdx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
Copy after login

Then, configure your globals.css file:

@tailwind base;
@tailwind components;
@tailwind utilities;
Copy after login

Orea Color Generator for Color Palette

Applying Dark Mode in Next.js using CSS Variables

To create a harmonious color palette for both light and dark modes, we can use the Orea Color Generator. This tool helps in generating a set of colors that work well together and can be easily adapted for different themes.

Visit the Orea Color Generator and select your base colors. The tool provides a user-friendly interface to create and visualize your color scheme:

The image above shows the Orea Color Generator interface, where you can:

  • Choose a middle color using the color picker
  • View generated colors in various shades
  • See a preview of your theme in both light and dark modes
  • Copy CSS variables for easy integration into your project

After generating your color palette with the Orea Color Generator, you’ll want to implement these colors in your project. Here’s an example of how you can define your color variables in CSS:

:root {
  /* Initially TailwindCSS bg-opacity */
  --tw-bg-opacity: 1;

  --primary-50: 242, 242, 242;
  --primary-100: 230, 230, 230;
  --primary-200: 204, 204, 204;
  --primary-300: 179, 179, 179;
  --primary-400: 153, 153, 153;
  --primary-500: 128, 128, 128;
  --primary-600: 102, 102, 102;
  --primary-700: 77, 77, 77;
  --primary-800: 51, 51, 51;
  --primary-900: 26, 26, 26;
  --primary-950: 13, 13, 13;
}
Copy after login

These CSS variables define a range of shades for your primary color, from lighter color ( — primary-50) to dark colors ( — primary-950). By using these variables, you can easily apply consistent colors throughout your application and switch between light and dark modes.

Now that we have our color variables defined, let’s integrate them into our Tailwind CSS configuration:

module.exports = {
  // ... other config
  theme: {
    extend: {
      colors: {
        primary: {
          '50': 'rgba(var(--primary-50), var(--tw-bg-opacity))',
          '100': 'rgba(var(--primary-100), var(--tw-bg-opacity))',
          '200': 'rgba(var(--primary-200), var(--tw-bg-opacity))',
          '300': 'rgba(var(--primary-300), var(--tw-bg-opacity))',
          '400': 'rgba(var(--primary-400), var(--tw-bg-opacity))',
          '500': 'rgba(var(--primary-500), var(--tw-bg-opacity))',
          '600': 'rgba(var(--primary-600), var(--tw-bg-opacity))',
          '700': 'rgba(var(--primary-700), var(--tw-bg-opacity))',
          '800': 'rgba(var(--primary-800), var(--tw-bg-opacity))',
          '900': 'rgba(var(--primary-900), var(--tw-bg-opacity))',
          '950': 'rgba(var(--primary-950), var(--tw-bg-opacity))',
        },
      },
    },
  },
}

Copy after login

This configuration allows you to use these colors in your Tailwind classes, like bg-primary-500 or text-primary-200, while still maintaining the ability to apply opacity using Tailwind’s opacity modifiers.

next-themes Package for Dark/Light Mode Theme

After installation, we need to set up our basic theme variables. Create a new CSS file (e.g., globals.css) or add to your existing one:

// app/layout.jsx
:root {
  /* Add your light mode colors */
  --tw-bg-opacity: 1;

  --primary-50: 242, 242, 242;
  --primary-100: 230, 230, 230;
  --primary-200: 204, 204, 204;
  --primary-300: 179, 179, 179;
}

[data-theme='dark'] {

/* Add your dark mode colors */
  --primary-50: 13, 13, 13;
  --primary-100: 26, 26, 26;
  --primary-200: 51, 51, 51;
  --primary-300: 77, 77, 77;
}
Copy after login

This CSS defines basic color variables for light and dark themes. The [data-theme=’dark’] selector will be automatically applied by next-themes when the dark mode is active.

Now, let’s implement the ThemeProvider in your layout.tsx file:

// app/layout.jsx

"use client";

import { ThemeProvider } from 'next-themes'

export default function Layout({ children }) {
  return (
    <html suppressHydrationWarning>
      <head />
      <body>
        <ThemeProvider>{children}</ThemeProvider>
      </body>
    </html>
  )
}
Copy after login

In your components, you can now use the useTheme hook to access and change the current theme:

"use client";

import { useTheme } from 'next-themes'

const ThemeChanger = () => {
  const { theme, setTheme } = useTheme()

  return (
    <div>
      The current theme is: {theme}
      <button onClick={() => setTheme('light')}>Light Mode</button>
      <button onClick={() => setTheme('dark')}>Dark Mode</button>
    </div>
  )
}

export default ThemeChanger
Copy after login

This setup allows for a smooth transition between light and dark modes, with the theme being persisted across page reloads.

Dropdown for Theme Toggle using shadcn/ui

For a more polished UI, we can use the dropdown component from shadcn/ui to create a theme toggle. First, install the necessary components:

npx shadcn-ui@latest add dropdown-menu
Copy after login

Now, let’s implement our theme toggle:

import { useTheme } from "next-themes"
import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Sun, Moon } from "lucide-react"

export function ThemeToggle() {
  const { setTheme } = useTheme()

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="outline" size="icon">
          <Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
          <Moon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
          <span className="sr-only">Toggle theme</span>
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end">
        <DropdownMenuItem onClick={() => setTheme("light")}>
          Light
        </DropdownMenuItem>
        <DropdownMenuItem onClick={() => setTheme("dark")}>
          Dark
        </DropdownMenuItem>
        <DropdownMenuItem onClick={() => setTheme("system")}>
          System
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  )
}
Copy after login

This component creates a dropdown menu with options to switch between light, dark, and system themes. The button uses sun and moon icons to visually represent the current theme.

Conclusion

Implementing dark mode in a Next.js application using CSS variables, Tailwind CSS, and next-themes provides a flexible and maintainable solution. Here’s a summary of what we’ve achieved:

  1. We set up Tailwind CSS for utility-first styling.
  2. We used the Orea Color Generator to create a consistent color palette for both light and dark modes.
  3. We implemented theme switching using next-themes, allowing for easy toggling between light and dark modes.
  4. We created a polished theme toggle component using shadcn/ui, enhancing the user experience.

By leveraging CSS variables, we’ve created a system that’s easy to maintain and extend. The use of next-themes ensures that our theme preference is persisted, providing a seamless experience for users.

Remember these key points when implementing dark mode:

  • Always consider accessibility and ensure sufficient contrast in both themes.
  • Test your application thoroughly in both light and dark modes.
  • Consider using prefers-color-scheme media query to respect the user’s system preferences.
  • Be consistent with your theming across all components and pages.

With this setup, you’re well-equipped to provide a modern, user-friendly dark mode option in your Next.js application. Happy coding!

The above is the detailed content of Applying Dark Mode in Next.js using CSS Variables. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1237
24
Google Fonts   Variable Fonts Google Fonts Variable Fonts Apr 09, 2025 am 10:42 AM

I see Google Fonts rolled out a new design (Tweet). Compared to the last big redesign, this feels much more iterative. I can barely tell the difference

How to Create an Animated Countdown Timer With HTML, CSS and JavaScript How to Create an Animated Countdown Timer With HTML, CSS and JavaScript Apr 11, 2025 am 11:29 AM

Have you ever needed a countdown timer on a project? For something like that, it might be natural to reach for a plugin, but it’s actually a lot more

HTML Data Attributes Guide HTML Data Attributes Guide Apr 11, 2025 am 11:50 AM

Everything you ever wanted to know about data attributes in HTML, CSS, and JavaScript.

A Proof of Concept for Making Sass Faster A Proof of Concept for Making Sass Faster Apr 16, 2025 am 10:38 AM

At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

How We Created a Static Site That Generates Tartan Patterns in SVG How We Created a Static Site That Generates Tartan Patterns in SVG Apr 09, 2025 am 11:29 AM

Tartan is a patterned cloth that’s typically associated with Scotland, particularly their fashionable kilts. On tartanify.com, we gathered over 5,000 tartan

How to Build Vue Components in a WordPress Theme How to Build Vue Components in a WordPress Theme Apr 11, 2025 am 11:03 AM

The inline-template directive allows us to build rich Vue components as a progressive enhancement over existing WordPress markup.

PHP is A-OK for Templating PHP is A-OK for Templating Apr 11, 2025 am 11:04 AM

PHP templating often gets a bad rap for facilitating subpar code — but that doesn&#039;t have to be the case. Let’s look at how PHP projects can enforce a basic

Programming Sass to Create Accessible Color Combinations Programming Sass to Create Accessible Color Combinations Apr 09, 2025 am 11:30 AM

We are always looking to make the web more accessible. Color contrast is just math, so Sass can help cover edge cases that designers might have missed.

See all articles