使用高级 Chakra UI 组件更快地构建 💎

了解更多

自定义深色模式颜色

2024年12月5日

您可以通过修改 Chakra UI 中的_dark 值来定制语义颜色令牌的深色模式颜色。本指南将向您展示如何覆盖默认的深色模式颜色。

自定义深色模式颜色

使用 createSystem 方法来覆盖主题配置中的深色模式颜色

components/theme.ts

const config = defineConfig({
  theme: {
    semanticTokens: {
      colors: {
        bg: {
          DEFAULT: {
            value: { _light: "{colors.white}", _dark: "#141414" }, // Custom dark background
          },
          subtle: {
            value: { _light: "{colors.gray.50}", _dark: "#1a1a1a" }, // Custom dark subtle background
          },
          muted: {
            value: { _light: "{colors.gray.100}", _dark: "#262626" }, // Custom dark muted background
          },
        },
        fg: {
          DEFAULT: {
            value: { _light: "{colors.black}", _dark: "#e5e5e5" }, // Custom dark text color
          },
          muted: {
            value: { _light: "{colors.gray.600}", _dark: "#a3a3a3" }, // Custom dark muted text
          },
        },
        border: {
          DEFAULT: {
            value: { _light: "{colors.gray.200}", _dark: "#404040" }, // Custom dark border
          },
        },
      },
    },
  },
})

export const system = createSystem(defaultConfig, config)
注意
要查看语义颜色令牌的完整列表,请参阅语义令牌源代码

接下来,将新的 system 添加到您的 components/ui/provider.tsx 文件中

"use client"

import { system } from "@/components/theme"
import { ChakraProvider } from "@chakra-ui/react"

export function Provider(props: ColorModeProviderProps) {
  return (
    <ChakraProvider value={system}>
      <ColorModeProvider {...props} />
    </ChakraProvider>
  )
}

理解语义颜色令牌

Chakra UI 中的语义颜色令牌遵循以下模式

{
  [colorKey]: {
    [variant]: {
      value: {
        _light: string, // Light mode value
        _dark: string   // Dark mode value
      }
    }
  }
}

常见的颜色键包括

每个颜色键都有以下变体

自定义特定调色板

您还可以为深色模式自定义特定的调色板

const config = defineConfig({
  theme: {
    semanticTokens: {
      colors: {
        blue: {
          solid: {
            value: { _light: "{colors.blue.600}", _dark: "#0284c7" }, // Custom dark blue
          },
          muted: {
            value: { _light: "{colors.blue.100}", _dark: "#082f49" }, // Custom dark muted blue
          },
        },
        // Add more color palettes as needed
      },
    },
  },
})

最佳实践

  1. 颜色对比度:确保您的自定义深色模式颜色保持足够的对比度以满足可访问性要求。

  2. 一致的调色板:通过使用一致的调色板,使您的深色模式颜色在整个应用程序中保持一致。

  3. 测试:始终在浅色和深色模式下测试您的自定义颜色,以确保良好的可读性和视觉和谐。

有关语义令牌的更多信息,请参阅语义令牌指南