Dark Mode
Implement dark mode with CSS variables and a simple toggle.
The implementation of dark mode is completely inspired by Shadcn ui , if you have already installed shadcn ui in your project, you can skip this guide and directly use dark mode in your project.You can also refer the Official documentation
How It Works
Dark mode is handled through the .dark class on the <html> element. When present, CSS variables switch to their dark variants automatically.
CSS Setup
Define both light and dark color schemes in your CSS:
globals.csscss
/* Light mode (default) */
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--primary: oklch(0.205 0 0);
/* ... other variables */
}
/* Dark mode */
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--primary: oklch(0.922 0 0);
/* ... other variables */
}Next.js Setup (Recommended)
For Next.js projects, we recommend using next-themes for seamless dark mode:
1. Install next-themes
Terminalbash
npm install next-themes2. Create Theme Provider
components/theme-provider.tsxtsx
"use client";
import * as React from "react";
import { ThemeProvider as NextThemesProvider } from "next-themes";
export function ThemeProvider({
children,
...props
}: React.ComponentProps<typeof NextThemesProvider>) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
}3. Wrap Your App
app/layout.tsxtsx
import { ThemeProvider } from "@/components/theme-provider";
export default function RootLayout({ children }) {
return (
<html lang="en" suppressHydrationWarning>
<body>
<ThemeProvider
attribute="class"
defaultTheme="dark"
enableSystem
disableTransitionOnChange
>
{children}
</ThemeProvider>
</body>
</html>
);
}Tips
- •Use
suppressHydrationWarningon<html>to avoid hydration mismatch warnings - •Set
enableSystemto respect user's OS preference - •Use
disableTransitionOnChangeto prevent flash during theme switch