스페이싱

스페이싱 (Spacing)

theme.spacing() 헬퍼를 쓰면 UI 요소들 사이의 간격을 일관되게 잡을 수 있어요. Material UI는 기본적으로 권장되는 8px 스케일 계수를 사용해서, 어떤 곳에서 사용하든 항상 조화로운 여백이 만들어집니다.

출처: 문서

본문

소개

theme.spacing() 헬퍼를 사용해서 UI 요소 사이의 간격을 일관되게 만들어보세요.

Material UI는 기본적으로 권장되는 8px 스케일 계수를 사용합니다.

const theme = createTheme();

theme.spacing(2); // `${8 * 2}px` = '16px'

커스텀 스페이싱 (Custom spacing)

스페이싱 변환을 바꾸려면 다음 중 하나를 제공하면 됩니다.

  • 숫자 (number)
const theme = createTheme({
  spacing: 4,
});

theme.spacing(2); // `${4 * 2}px` = '8px'
  • 함수 (function)
const theme = createTheme({
  spacing: (factor) => `${0.25 * factor}rem`, // (Bootstrap strategy)
});

theme.spacing(2); // = 0.25 * 2rem = 0.5rem = 8px
  • 배열 (array)
const theme = createTheme({
  spacing: [0, 4, 8, 16, 32, 64],
});

theme.spacing(2); // = '8px'

:::warning 스페이싱을 배열로 정의하면, 배열 인덱스로 사용되는 양의 정수에서만 동작한다는 점을 꼭 기억해두세요.

theme.spacing(0.5), theme.spacing(-1), 혹은 theme.spacing(1, 'auto')처럼 theme.spacing() 헬퍼가 지원하는 모든 시그니처를 받아주지는 않아요.

어쩔 수 없이 스페이싱 배열을 써야 한다면, theme.spacing() 헬퍼가 지원하는 모든 시그니처를 처리할 수 있는 함수 시그니처를 사용하는 쪽을 고려해보세요.

스페이싱 함수 예시 (Spacing function example)
const spacings = [0, 4, 8, 16, 32, 64];

const theme = createTheme({
  spacing: (factor: number | 'auto' = 1) => {
    if (factor === 'auto') {
      return 'auto';
    }
    const sign = factor >= 0 ? 1 : -1;
    const factorAbs = Math.min(Math.abs(factor), spacings.length - 1);
    if (Number.isInteger(factor)) {
      return spacings[factorAbs] * sign;
    }
    return interpolate(factorAbs, spacings) * sign;
  },
});

const interpolate = (value: number, array: readonly number[]) => {
  const floor = Math.floor(value);
  const ceil = Math.ceil(value);
  const diff = value - floor;
  return array[floor] + (array[ceil] - array[floor]) * diff;
};
:::

여러 인자 (Multiple arity)

theme.spacing() 헬퍼는 최대 4개의 인자를 받아요. 인자를 활용하면 반복되는 코드를 줄일 수 있습니다.

-padding: `${theme.spacing(1)} ${theme.spacing(2)}`, // '8px 16px'
+padding: theme.spacing(1, 2), // '8px 16px'

문자열 값과 섞어 쓰는 것도 지원합니다.

margin: theme.spacing(1, 'auto'), // '8px auto'

더 알아보기 (Learn more)

  • Material UI 테마 커스터마이징