search
HomeWeb Front-endCSS TutorialApplying Dark Mode in Next.js using CSS Variables

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

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: [],
}

Then, configure your globals.css file:

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

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;
}

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))',
        },
      },
    },
  },
}

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;
}

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 (
    
      
{children} ) }

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

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

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"></sun>
          <moon classname="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"></moon>
          <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>
  )
}

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
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
Demystifying Screen Readers: Accessible Forms & Best PracticesDemystifying Screen Readers: Accessible Forms & Best PracticesMar 08, 2025 am 09:45 AM

This is the 3rd post in a small series we did on form accessibility. If you missed the second post, check out "Managing User Focus with :focus-visible". In

Create a JavaScript Contact Form With the Smart Forms FrameworkCreate a JavaScript Contact Form With the Smart Forms FrameworkMar 07, 2025 am 11:33 AM

This tutorial demonstrates creating professional-looking JavaScript forms using the Smart Forms framework (note: no longer available). While the framework itself is unavailable, the principles and techniques remain relevant for other form builders.

Adding Box Shadows to WordPress Blocks and ElementsAdding Box Shadows to WordPress Blocks and ElementsMar 09, 2025 pm 12:53 PM

The CSS box-shadow and outline properties gained theme.json support in WordPress 6.1. Let's look at a few examples of how it works in real themes, and what options we have to apply these styles to WordPress blocks and elements.

Working With GraphQL CachingWorking With GraphQL CachingMar 19, 2025 am 09:36 AM

If you’ve recently started working with GraphQL, or reviewed its pros and cons, you’ve no doubt heard things like “GraphQL doesn’t support caching” or

Making Your First Custom Svelte TransitionMaking Your First Custom Svelte TransitionMar 15, 2025 am 11:08 AM

The Svelte transition API provides a way to animate components when they enter or leave the document, including custom Svelte transitions.

Comparing the 5 Best PHP Form Builders (And 3 Free Scripts)Comparing the 5 Best PHP Form Builders (And 3 Free Scripts)Mar 04, 2025 am 10:22 AM

This article explores the top PHP form builder scripts available on Envato Market, comparing their features, flexibility, and design. Before diving into specific options, let's understand what a PHP form builder is and why you'd use one. A PHP form

Show, Don't TellShow, Don't TellMar 16, 2025 am 11:49 AM

How much time do you spend designing the content presentation for your websites? When you write a new blog post or create a new page, are you thinking about

What the Heck Are npm Commands?What the Heck Are npm Commands?Mar 15, 2025 am 11:36 AM

npm commands run various tasks for you, either as a one-off or a continuously running process for things like starting a server or compiling code.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft