apps/www/content/docs/styling/dark-mode.mdx
Chakra relies on the next-themes library to provide dark mode support. During
the installation process, the snippets required to get started are added to your
project via the CLI.
To implement color mode in your components, you can use:
bg.subtle that automatically adapt to light/dark mode._dark overrides: Manually specify dark mode styles for each color
property.If you haven't already, you can add the next-themes library to your project
via the CLI.
npx @chakra-ui/cli snippet add color-mode
The generated snippets consists of the following:
ColorModeProvider: composes the next-themes provider componentuseColorMode: provides the current color mode and a function to toggle the
color modeuseColorModeValue: returns the correct value based on the current color modeColorModeButton: can be used to toggle the color modeWrap your app with the ColorModeProvider and use the useColorMode hook to
access and toggle the color mode.
import { ColorModeProvider } from "@/components/ui/color-mode"
import { ChakraProvider, defaultSystem } from "@chakra-ui/react"
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<ChakraProvider value={defaultSystem}>
<ColorModeProvider>{children}</ColorModeProvider>
</ChakraProvider>
)
}
Use the ColorModeButton component to toggle the color mode.
import { ColorModeButton } from "@/components/ui/color-mode"
export default function Page({ children }: { children: React.ReactNode }) {
return (
<>
<ColorModeButton />
{children}
</>
)
}
Use the _dark condition to style components for dark mode.
<Box bg={{ base: "white", _dark: "black" }}>
<Text>Hello</Text>
</Box>
or
<Box bg="white" _dark={{ bg: "black" }}>
<Text>Hello</Text>
</Box>
To reduce the amount of code you need to write, use semantic tokens to style components for dark mode. This ensures the light and dark mode styles are applied automatically and consistently.
Chakra provides a set of semantic tokens that you can use to style components for dark mode. Learn more about semantic tokens.
<Box bg="bg.subtle">
<Text>Hello</Text>
</Box>
To force dark mode, set the dark className on any parent element, or the root
element of your application.
<Box bg="black" className="dark">
<Box bg="bg.subtle">
<Text>Hello</Text>
</Box>
</Box>
The same applied to forcing light mode, use the light className.
<Box bg="white" className="light">
<Box bg="bg.subtle">
<Text>Hello</Text>
</Box>
</Box>
Use the ColorModeProvider component to set the dark mode for a page.
<ColorModeProvider forcedTheme="dark">
<Box bg="black" className="dark">
<Box bg="bg.subtle">
<Text>Hello</Text>
</Box>
</Box>
</ColorModeProvider>
Follow this
next-themesguide to learn more about forcing color mode.