본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Palette

원문 보기 위키 갱신

Palette (팔레트)

팔레트를 사용하면 컴포넌트의 색상을 브랜드에 맞게 수정할 수 있습니다.

출처: 문서

본문

색상 토큰 (Color tokens)

팔레트 색상은 네 가지 토큰으로 표현됩니다:

  • main: 색상의 메인 셰이드
  • light: main의 더 밝은 셰이드
  • dark: main의 더 어두운 셰이드
  • contrastText: main과 대비되도록 의도된 텍스트 색상

Material UI의 기본 테마가 primary 색상 토큰을 정의하는 방법은 다음과 같습니다:

const primary = {
  main: '#1976d2',
  light: '#42a5f5',
  dark: '#1565c0',
  contrastText: '#fff',
};

Material Design 색상 시스템에 대한 자세한 내용은 Color 문서를 참고하세요.

기본 색상 (Default colors)

테마는 다음과 같은 기본 팔레트 색상을 노출합니다(theme.palette.* 아래에서 접근 가능):

  • primary - 기본 인터페이스 요소용.
  • secondary - 보조 인터페이스 요소용.
  • error - 사용자가 인지해야 하는 요소용.
  • warning - 잠재적으로 위험한 동작이나 중요한 메시지용.
  • info - 중립적인 정보를 강조하기 위한 것.
  • success - 사용자가 트리거한 동작의 성공적 완료를 나타내기 위한 것.

색상 사용과 가이드라인에 대한 자세한 내용은 Material Design의 Color System을 참고하세요.

값 (Values)

테마 탐색기를 사용하거나 이 페이지에서 개발자 도구 콘솔을 열어(window.theme.palette) 기본 팔레트 값을 탐색할 수 있습니다.

{{"demo": "Intentions.js", "bg": "inline", "hideToolbar": true}}

기본 팔레트는 secondary 팔레트 색상에 대해 A 접두사(A200 등)가 붙은 셰이드를 사용하고, 다른 팔레트 색상에는 접두사가 없는 셰이드를 사용합니다.

커스터마이즈 (Customization)

테마의 일부로 팔레트 객체를 포함하여 기본 팔레트 값을 오버라이드할 수 있습니다. 다음 중 하나라도:

팔레트 색상 객체가 제공되면 기본값을 대체합니다.

이는 색상 객체를 사용하거나 색상을 직접 제공하는 두 가지 방식으로 달성할 수 있습니다:

색상 객체 사용하기 (Using a color object)

팔레트 색상을 커스터마이즈하는 가장 직접적인 방법은 아래와 같이 하나 이상의 색상 객체를 import하고 적용하는 것입니다:

{{"demo": "UsingColorObject.js", "defaultCodeOpen": true}}

색상을 직접 제공하기 (Providing the colors directly)

각 색상을 직접 수정하려면 색상 토큰 중 하나 이상이 포함된 객체를 제공하세요. main 토큰만 필요하며, light, dark, contrastText는 선택 사항이고 제공하지 않으면 값이 자동으로 계산됩니다:

import { createTheme } from '@mui/material/styles';

const theme = createTheme({
  palette: {
    primary: {
      main: '#FF5733',
      // light: will be calculated from palette.primary.main,
      // dark: will be calculated from palette.primary.main,
      // contrastText: will be calculated to contrast with palette.primary.main
    },
    secondary: {
      main: '#E0C2FF',
      light: '#F5EBFF',
      // dark: will be calculated from palette.secondary.main,
      contrastText: '#47008F',
    },
  },
});
{{"demo": "ManuallyProvidePaletteColor.js", "defaultCodeOpen": false}}

대비 임계값 (Contrast threshold)

contrastText 토큰은 배경과 텍스트 간의 대비를 극대화하기 위해 contrastThreshold 값을 사용해 계산됩니다.

대비 임계값이 높을수록 배경색이 밝은 것으로 간주되는 지점이 올라가므로, 더 어두운 contrastText가 주어집니다. 대비 임계값은 비선형 곡선을 따르며, 기본값은 3으로 최소 대비 비율 3:1을 나타냅니다.

{{"demo": "ContrastThreshold.js", "defaultCodeOpen": false}}

톤 오프셋 (Tonal offset)

light와 dark 토큰은 main 색상의 휘도(luminance)를 이동시키기 위해 tonalOffset 값을 사용해 계산됩니다. 톤 오프셋 값이 높을수록 light 토큰은 더 밝아지고 dark 토큰은 더 어두워집니다.

:::warning 이는 커스텀 색상으로 작업할 때만 적용됩니다—기본값에는 영향을 주지 않습니다. :::

예를 들어 톤 오프셋 기본값 0.2는 휘도를 대략 두 인덱스만큼 이동시키므로, main 토큰이 blue[500]이면 light 토큰은 blue[300]이 되고 dark는 blue[700]이 됩니다.

톤 오프셋 값은 0과 1 사이의 숫자(light와 dark 토큰 모두에 적용됨)이거나 light와 dark 키가 지정된 객체일 수 있습니다:

{{"demo": "TonalOffset.js", "defaultCodeOpen": false}}

커스텀 색상 (Custom colors)

:::warning 기본 색상과 달리 커스텀 색상의 토큰은 자동으로 계산되지 않습니다. :::

커스텀 색상을 추가하려면 토큰을 수동으로 제공하거나 augmentColor 유틸리티로 생성해야 합니다:

토큰을 수동으로 제공하기

가장 간단한 방법은 main, light, dark, contrastText 모든 토큰을 수동으로 정의하는 것입니다:

import { createTheme } from '@mui/material/styles';

const theme = createTheme({
  palette: {
    ochre: {
      main: '#E3D026',
      light: '#E9DB5D',
      dark: '#A29415',
      contrastText: '#242105',
    },
  },
});
{{"demo": "ManuallyProvideCustomColor.js", "defaultCodeOpen": false}}

:::info 지원되는 색상 형식은 hex, rgb, hsl입니다. oklch와 같은 다른 형식을 사용하려면 네이티브 색상 기능을 활성화해야 합니다. :::

색상을 조작해야 한다면 @mui/material/styles가 유틸리티 세트를 제공해 도와줍니다. 다음 예시는 alpha()와 getContrastRatio() 유틸리티를 사용해 불투명도로 토큰을 정의합니다:

import { createTheme, alpha, getContrastRatio } from '@mui/material/styles';

const violetBase = '#7F00FF';
const violetMain = alpha(violetBase, 0.7);

const theme = createTheme({
  palette: {
    violet: {
      main: violetMain,
      light: alpha(violetBase, 0.5),
      dark: alpha(violetBase, 0.9),
      contrastText: getContrastRatio(violetMain, '#fff') > 4.5 ? '#fff' : '#111',
    },
  },
});
{{"demo": "UsingStylesUtils.js", "defaultCodeOpen": false}}

augmentColor 유틸리티로 토큰 생성하기

또는 기본 팔레트 색상에 사용되는 것과 동일한 함수인 팔레트의 augmentColor 유틸리티로 light, dark, contrastText 토큰을 생성할 수 있습니다. 이를 위해서는 테마를 두 단계로 만들고 다른 토큰의 기반이 될 main 토큰을 제공해야 합니다:

import { createTheme } from '@mui/material/styles';

let theme = createTheme({
  // Theme customization goes here as usual, including tonalOffset and/or
  // contrastThreshold as the augmentColor() function relies on these
});

theme = createTheme(theme, {
  // Custom colors created with augmentColor go here
  palette: {
    salmon: theme.palette.augmentColor({
      color: {
        main: '#FF5733',
      },
      name: 'salmon',
    }),
  },
});
{{"demo": "UsingAugmentColor.js", "defaultCodeOpen": false}}

대비 임계값과 톤 오프셋 값이 이 유틸리티를 사용해 정의된 색상에 적용됩니다.

컴포넌트에서 사용하기

커스텀 색상을 추가한 후에는 기본 팔레트 색상과 마찬가지로 컴포넌트에서 사용할 수 있습니다:

<Button color="custom">

TypeScript

TypeScript를 사용한다면 커스텀 색상에 모듈 증강을 사용해야 합니다.

팔레트에 커스텀 색상을 추가하려면 Palette와 PaletteOptions 인터페이스에 추가해야 합니다:

declare module '@mui/material/styles' {
  interface Palette {
    custom: Palette['primary'];
  }

  interface PaletteOptions {
    custom?: PaletteOptions['primary'];
  }
}

컴포넌트의 color prop에 커스텀 색상을 사용하려면 컴포넌트의 PropsColorOverrides 인터페이스에 추가해야 합니다. 아래 예시는 Button 컴포넌트로 이 방법을 보여줍니다:

declare module '@mui/material/Button' {
  interface ButtonPropsColorOverrides {
    custom: true;
  }
}

색상 토큰 추가하기 (Adding color tokens)

새 색상 토큰을 추가하려면 다음과 같이 색상의 객체에 포함하세요:

import { createTheme } from '@mui/material/styles';
import { blue } from '@mui/material/colors';

const theme = createTheme({
  palette: {
    primary: {
      light: blue[300],
      main: blue[500],
      dark: blue[700],
      darker: blue[900],
    },
  },
});
{{"demo": "AddingColorTokens.js", "defaultCodeOpen": false}}

TypeScript

TypeScript를 사용한다면, 다음과 같이 PaletteColor와 SimplePaletteColorOptions 인터페이스에 새 색상 토큰을 추가하기 위해 모듈 증강을 사용해야 합니다:

declare module '@mui/material/styles' {
  interface PaletteColor {
    darker?: string;
  }

  interface SimplePaletteColorOptions {
    darker?: string;
  }
}

팔레트가 아닌 색상 (Non-palette colors)

theme.palette 밖에 색상을 추가하는 방법을 배우려면 Theming—Custom variables를 참고하세요.

접근성 (Accessibility)

WCAG 2.2 Success Criterion 1.4.3에 정의된 최소 4.5:1 대비를 충족하려면 다음과 같이 대비 임계값이 4.5인 커스텀 테마를 만드세요:

import { createTheme } from '@mui/material/styles';

const theme = createTheme({
  palette: {
    contrastThreshold: 4.5,
  },
});

:::warning contrastThreshold 매개변수는 역효과를 낼 수 있습니다. APCA 색상 대비가 개선되는지 확인하세요(WCAG 3 이 새 알고리즘을 사용할 것입니다). :::

Windows 고대비 모드 (Windows High Contrast mode)

Windows 고대비 모드(Forced Colors라고도 함)에서 컴포넌트 가시성을 개선하려면 v9.1.0부터 enhanceHighContrast 테마 강화자를 사용하세요. 이 함수는 완전히 생성된 테마를 받아 영향받는 컴포넌트에 @media (forced-colors: active) 오버라이드를 적용한 향상된 버전을 반환합니다.

import { createTheme, enhanceHighContrast } from '@mui/material/styles';

const theme = enhanceHighContrast(createTheme());

기본적으로 CSS 시스템 색상 키워드(Highlight, HighlightText, ButtonBorder 등)를 사용합니다. 브랜드나 디자인 요구 사항에 맞게 개별 토큰을 다른 시스템 색상으로 오버라이드할 수 있습니다. 쌍을 이루는 토큰을 오버라이드할 때는 브라우저가 서로 대비를 보장하는 값을 선택하세요—예를 들어 SelectedItem은 항상 SelectedItemText와 쌍을 이루고, Highlight는 HighlightText와 쌍을 이룹니다:

import { createTheme, enhanceHighContrast } from '@mui/material/styles';

const theme = enhanceHighContrast(createTheme(), {
  // Use the system's selection colors for active or toggled controls.
  activeBackground: 'SelectedItem',
  activeText: 'SelectedItemText',
});

다음 토큰을 사용할 수 있으며, 현재 환경에서 브라우저가 각 시스템 색상 키워드를 어떻게 해석하는지 보여줍니다:

{{"demo": "HighContrastTokens.js", "bg": "inline", "hideToolbar": true}}

색상 고르기 (Picking colors)

영감이 필요하신가요? Material Design 팀이 도와줄 팔레트 구성 도구를 만들었습니다.

색상 스킴 (Color schemes)

별도의 테마를 만들지 않고 내장 light와 dark 색상 스킴을 모두 추가하려면 colorSchemes: { light: true, dark: true }를 사용하세요. 이것은 두 색상 스킴 모두에 대해 기본 토큰을 생성합니다:

import { createTheme } from '@mui/material/styles';

const theme = createTheme({
  colorSchemes: {
    light: true,
    dark: true,
  },
});

각 색상 스킴의 기본 토큰을 오버라이드하려면 아래와 같이 동일한 팔레트 객체를 사용하세요:

const theme = createTheme({
  colorSchemes: {
    light: {
      palette: {
        primary: {
          main: '#FF5733',
        },
        // ...other tokens
      },
    },
    dark: {
      palette: {
        primary: {
          main: '#E0C2FF',
        },
        // ...other tokens
      },
    },
  },
});

:::warning colorSchemes API는 palette API의 강화된 버전이며, Material UI v6부터 이 목적에 권장되는 API입니다. colorSchemes와 palette를 모두 제공하면 후자가 전자에 정의된 스타일을 오버라이드합니다.

const theme = createTheme({
  palette: {
    primary: {
      main: '...',
    },
  },
  colorSchemes: {
    light: {
      // This will be replaced by the palette defined above
      palette: {
        primary: {
          main: '...',
        },
      },
    },
    dark: { ... },
  },
});

:::

다크 모드 (Dark mode)

테마에 다크 모드를 설정하는 방법에 대한 자세한 내용은 다크 모드 가이드로 이동하세요.

더 알아보기 (Learn more)