Typography
테마는 서로 잘 어울리고 레이아웃 그리드와도 잘 맞는 일련의 글자 크기(type sizes)를 제공해요.
출처: 문서
본문
폰트 패밀리
폰트 패밀리는 theme.typography.fontFamily 속성으로 바꿀 수 있어요.
예를 들어 아래 예시는 기본 Roboto 폰트 대신 시스템 폰트를 사용해요.
const theme = createTheme({
typography: {
fontFamily: [
'-apple-system',
'BlinkMacSystemFont',
'"Segoe UI"',
'Roboto',
'"Helvetica Neue"',
'Arial',
'sans-serif',
'"Apple Color Emoji"',
'"Segoe UI Emoji"',
'"Segoe UI Symbol"',
].join(','),
},
});
셀프 호스팅 폰트
폰트를 직접 호스팅하려면 woff2 형식으로 폰트 파일을 다운로드해 코드에 임포트해 주세요.
:::warning
빌드 과정에 woff2 파일 로딩을 처리할 수 있는 플러그인 이나 로더가 있어야 해요. 폰트는 번들에 내장되지 않고, CDN 대신 여러분의 웹서버에서 로드돼요.
:::
import RalewayWoff2 from './fonts/Raleway-Regular.woff2';
다음으로 테마를 바꿔 이 새 폰트를 사용해야 해요. Raleway를 폰트 페이스로 전역 정의하려면 CssBaseline 컴포넌트를 사용할 수 있어요(혹은 원하는 다른 CSS 솔루션).
import RalewayWoff2 from './fonts/Raleway-Regular.woff2';
const theme = createTheme({
typography: {
fontFamily: 'Raleway, Arial',
},
components: {
MuiCssBaseline: {
styleOverrides: `
@font-face {
font-family: 'Raleway';
font-style: normal;
font-display: swap;
font-weight: 400;
src: local('Raleway'), local('Raleway-Regular'), url(${RalewayWoff2}) format('woff2');
unicodeRange: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF;
}
`,
},
},
});
// ...
return (
<ThemeProvider theme={theme}>
<CssBaseline />
<Box sx={{ fontFamily: 'Raleway' }}>Raleway</Box>
</ThemeProvider>
);
추가 @font-face 선언을 더하고 싶다면 스타일 오버라이드에 문자열 CSS 템플릿 문법을 사용해야 해요. 그래야 앞서 정의한 @font-face 선언이 교체되지 않아요.
폰트 크기
Material UI는 폰트 크기에 rem 단위를 사용해요. 브라우저 <html> 요소의 기본 폰트 크기는 16px인데, 브라우저에는 이 값을 바꿀 수 있는 옵션이 있어요. 그래서 rem 단위를 사용하면 사용자 설정을 반영해서 접근성을 더 잘 지원할 수 있어요. 사용자들은 나쁜 시력부터 크기와 시청 거리가 크게 다른 기기에서의 최적 설정까지 다양한 이유로 폰트 크기 설정을 바꿔요.
Material UI의 폰트 크기를 바꾸려면 fontSize 속성을 제공하면 돼요. 기본값은 14px예요.
const theme = createTheme({
typography: {
// In Chinese and Japanese the characters are usually larger,
// so a smaller fontsize may be appropriate.
fontSize: 12,
},
});
브라우저가 계산하는 폰트 크기는 다음 수학식에 따릅니다:
반응형 폰트 크기
theme.typography.* variant 속성은 생성된 CSS에 직접 매핑돼요. 그 안에서 미디어 쿼리를 사용할 수 있어요.
const baseTheme = createTheme();
const theme = createTheme({
typography: {
h3: {
fontSize: '1.2rem',
'@media (min-width:600px)': {
fontSize: '1.5rem',
},
[baseTheme.breakpoints.up('md')]: {
fontSize: '2.4rem',
},
},
},
});
{{"demo": "CustomResponsiveFontSizes.js"}}
이 설정을 자동화하려면 responsiveFontSizes() 헬퍼를 사용해서 테마 안의 Typography 폰트 크기를 반응형으로 만들 수 있어요.
{{"demo": "ResponsiveFontSizesChart.js", "hideToolbar": true}}
아래 예시에서 직접 확인해 볼 수 있어요. 브라우저 창 크기를 조절하면 폭이 다양한 breakpoints를 넘어갈 때 폰트 크기가 바뀌는 걸 볼 수 있어요.
import { createTheme, responsiveFontSizes } from '@mui/material/styles';
let theme = createTheme();
theme = responsiveFontSizes(theme);
{{"demo": "ResponsiveFontSizes.js"}}
유동 폰트 크기
준비 중이에요: #15251.
HTML 폰트 크기
<html> 요소의 기본 폰트 크기를 바꾸고 싶을 수도 있어요. 예를 들어 10px 단순화를 쓸 때 그렇죠.
:::warning 폰트 크기를 바꾸면 접근성을 해칠 수 있어요 ♿️. 대부분의 브라우저는 기본 크기 16px에 동의하지만, 사용자가 그것을 바꿀 수 있어요. 예를 들어 시력이 나쁜 사람은 브라우저 기본 폰트 크기를 더 크게 설정할 수 있죠. :::
theme.typography.htmlFontSize 속성이 이런 용도로 제공돼요. 이 속성은 <html> 요소의 폰트 크기가 얼마인지를 Material UI에 알려 줘요. 계산된 폰트 크기가 항상 사양과 일치하도록 rem 값을 조정하는 데 사용돼요.
const theme = createTheme({
typography: {
// Tell Material UI what the font-size on the html element is.
htmlFontSize: 10,
},
});
html {
font-size: 62.5%; /* 62.5% of 16px = 10px */
}
아래 데모가 올바르게 렌더링되려면 이 페이지의 HTML 요소에 위 CSS를 적용해야 해요.
{{"demo": "FontSizeTheme.js"}}
Variants
typography 객체는 기본적으로 13개의 variants를 제공해요.
- h1
- h2
- h3
- h4
- h5
- h6
- subtitle1
- subtitle2
- body1
- body2
- button
- caption
- overline
이 variants 각각을 개별적으로 커스터마이징할 수 있어요.
const theme = createTheme({
typography: {
subtitle1: {
fontSize: 12,
},
body1: {
fontWeight: 500,
},
button: {
fontStyle: 'italic',
},
},
});
{{"demo": "TypographyVariants.js"}}
Variants 추가 & 비활성화
기본 typography variants를 쓰는 것 외에 커스텀 variants를 추가하거나, 필요 없는 것을 비활성화할 수 있어요. 이렇게 하면 돼요.
1단계. 테마의 typography 객체 업데이트
아래 코드 조각은 poster라는 커스텀 variant를 테마에 추가하고, 기본 h3 variant는 제거해요.
const theme = createTheme({
typography: {
poster: {
fontSize: '4rem',
color: 'red',
},
// Disable h3 variant
h3: undefined,
},
});
2단계. (선택) 새 variant의 기본 의미 요소 설정
이 시점에서 이미 새 poster variant를 사용할 수 있어요. 기본적으로 커스텀 스타일이 적용된 <span>으로 렌더링돼요. 의미(semantic)를 위해 다른 HTML 요소를 기본으로 쓰고 싶거나, 스타일링을 위해 인라인 <span>을 블록 레벨 요소로 바꾸고 싶을 때가 있어요.
그럴 때는 테마 레벨에서 Typography 컴포넌트의 variantMapping prop을 전역으로 업데이트해 주세요.
const theme = createTheme({
typography: {
poster: {
fontSize: 64,
color: 'red',
},
// Disable h3 variant
h3: undefined,
},
components: {
MuiTypography: {
defaultProps: {
variantMapping: {
// Map the new variant to render a <h1> by default
poster: 'h1',
},
},
},
},
});
3단계. 필요한 타입 정의 업데이트 (TypeScript 사용 시)
:::info TypeScript를 사용하지 않는다면 이 단계는 건너뛰어도 돼요. :::
테마의 typography variants와 Typography의 variant prop에 대한 타입 정의가 새로운 variants 집합을 반영하도록 해야 해요.
declare module '@mui/material/styles' {
interface TypographyVariants {
poster: React.CSSProperties;
}
// allow configuration using `createTheme()`
interface TypographyVariantsOptions {
poster?: React.CSSProperties;
}
}
// Update the Typography's variant prop options
declare module '@mui/material/Typography' {
interface TypographyPropsVariantOverrides {
poster: true;
h3: false;
}
}
4단계. 이제 새 variant를 사용할 수 있어요
{{"demo": "TypographyCustomVariant.js", "hideToolbar": true}}
<Typography variant="poster">poster</Typography>;
/* This variant is no longer supported. If you are using TypeScript it will give an error */
<Typography variant="h3">h3</Typography>;
기본값
typography의 기본값은 테마 탐색기를 사용하거나, 이 페이지의 개발자 도구 콘솔(window.theme.typography)에서 확인할 수 있어요.