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

rem, em, px 단위

원문 보기 위키 갱신

Mantine 컴포넌트는 크기 관련 스타일(margin, padding, width 등)을 모두 rem 단위로 적용해요. 기본적으로 1rem은 대부분 브라우저의 기본 설정인 16px로 간주되며, 모든 컴포넌트는 사용자의 브라우저 font-size 설정 또는 html/:root 요소의 font-size에 맞춰 자동으로 크기가 조정돼요.

출처: 문서

본문

rem 단위

Mantine의 모든 컴포넌트는 크기 스타일(margin, padding, width 등)을 적용할 때 rem 단위를 사용해요. 기본적으로 1rem은 대부분 브라우저의 기본값인 16px로 간주해요. 모든 컴포넌트는 사용자의 브라우저 font-size 설정 또는 html/:root 요소의 font-size에 따라 크기가 조정돼요.

import { Slider } from '@mantine/core';

function Demo() {
  return (
    <Slider
      onChange={(value) => {
        document.documentElement.style.fontSize = `${value}%`;
      }}
    />
  );
}

rem 단위 조정

:root/html 요소의 font-size를 바꾸면서 Mantine 컴포넌트 크기도 함께 유지하고 싶다면, theme에 scale을 1 / htmlFontSize 값으로 설정하면 돼요.

예를 들어 html font-size를 10px로 설정하고 Mantine 컴포넌트를 그에 맞게 조정하려면 scale을 1 / (10 / 16)(16은 기본 font-size) = 1 / 0.625 = 1.6으로 설정하면 돼요:

:root {
  font-size: 10px;
}
import { createTheme, MantineProvider } from '@mantine/core';

const theme = createTheme({
  scale: 1.6,
});

function Demo() {
  return (
    <MantineProvider theme={theme}>
      {/* Your app here */}
    </MantineProvider>
  );
}

em 단위

em 단위는 미디어 쿼리에서 rem 단위와 같은 방식으로 사용되지만, html/:root 요소에 지정된 font-size의 영향을 받지 않아요. 1em은 16px로 간주해요.

px 변환

일부 Mantine 컴포넌트의 props에는 숫자를 사용할 수 있어요. 숫자는 px로 취급되어 rem으로 변환돼요. 예를 들어:

import { ColorSwatch } from '@mantine/core';

function DemoPx() {
  // ColorSwatch 크기를 px로 지정하면 자동으로 rem으로 변환돼요
  // 이 경우 ColorSwatch의 너비와 높이는 32px / 16 = 2rem이 돼요
  return <ColorSwatch size={32} />;
}

function DemoRem() {
  // 이 데모는 앞선 것과 동일한 크기를 가져요
  return <ColorSwatch size="2rem" />;
}

같은 변환이 style props에서도 일어나요:

import { Box } from '@mantine/core';

function Demo() {
  // width: calc(2rem * var(--mantine-scale))
  // height: calc(1rem * var(--mantine-scale))
  return <Box w={32} h={16} />;
}

rem, em 함수

@mantine/core 패키지는 px를 rem/em으로 변환하는 rem, em 함수를 내보내요:

import { em, rem } from '@mantine/core';

// 숫자와 px 단위 값은 rem으로 변환돼요
rem(32); // -> calc(2rem * var(--mantine-scale))
em(32); // -> 2em
rem('16px'); // -> calc(1rem * var(--mantine-scale))
em('16px'); // -> 1em

rem('2rem'); // -> 2rem
em('2rem'); // -> 2rem

rem('50%'); // -> 50%
em('50%'); // -> 50%

rem('5vh'); // -> 5vh
em('5vh'); // -> 5vh

// 혼합된 값도 rem으로 변환돼요
rem('16px 2rem'); // -> calc(1rem * var(--mantine-scale)) 2rem

rem을 px로 변환

rem/em을 px로 변환하려면 @mantine/core에서 내보내는 px 함수를 사용하면 돼요:

import { px } from '@mantine/core';

px('2rem'); // -> 32
px('10rem'); // -> 160

css 파일에서 rem/em 함수 사용

postcss-preset-mantine이 설치되어 있다면 css 파일에서 rem, em 함수를 사용할 수 있어요:

.demo {
  font-size: rem(16px);

  @media (min-width: em(320px)) {
    font-size: rem(32px);
  }
}

css 파일에서 px를 rem으로 자동 변환

css 파일에서 px를 rem으로 자동 변환하려면 postcss-preset-mantine 설정에서 autoRem 옵션을 활성화하면 돼요:

module.exports = {
  plugins: {
    'postcss-preset-mantine': {
      autoRem: true,
    },
  },
};

더 알아보기 (Learn more)