Skip to content
Theme UI

Color Modes

Color modes can be used to create a user-configurable dark mode or any number of other color modes.

Defining colors

In the theme.colors object, add a nested modes object that will contain keys for optional color modes. Add an initialColorMode value to the theme to initialize the default state.

// example theme colors
// this enables the color modes feature
// and is used as the name for the top-level colors object
initialColorMode: 'light',
// optionally enable custom properties
// to help avoid a flash of colors on page load
useCustomProperties: true,
colors: {
text: '#000',
background: '#fff',
primary: '#07c',
modes: {
dark: {
text: '#fff',
background: '#000',
primary: '#0cf',

Setting the color mode

Use the useColorMode hook in your application to change the color mode. This value will be stored in localStorage and used whenever the page is loaded.

import React from 'react'
import { useColorMode } from 'theme-ui'
export default props => {
const [colorMode, setColorMode] = useColorMode()
return (
onClick={e => {
setColorMode(colorMode === 'light' ? 'dark' : 'light')
Toggle {colorMode === 'light' ? 'Dark' : 'Light'}

Applying colors

The previous steps will enable a color mode state and pass it through context. To apply the color mode values to the <body> element, render the ColorMode component in your application.

If you're using Gatsby to build your app, follow the instructions below.

import React from 'react'
import { ThemeProvider, ColorMode } from 'theme-ui'
import theme from './theme'
export default props => (
<ThemeProvider theme={theme}>
<ColorMode />

Gatsby plugin

For use in a Gatsby site, install and use gatsby-plugin-theme-ui to add the ThemeProvider to the root of your application. The plugin will help prevent the flash of colors that can happen during page load when a user has a non-default color mode set. If you support CSS custom properties, we recommend setting useCustomProperties in your theme.

npm i gatsby-plugin-theme-ui

This plugin will look for a src/gatsby-plugin-theme-ui/index.js file to import and pass to the ThemeProvider.

// gatsby-config.js
module.exports = {
plugins: ['gatsby-plugin-theme-ui'],

See the Gatsby plugin docs for more info.

Edit the page on GitHub
Styling MDX