CSS Variables
Ionic 컴포넌트는 앱을 쉽게 커스터마이즈할 수 있도록 CSS Variables 기반으로 만들어졌습니다. CSS 변수를 사용하면 값을 한 곳에 저장해 두고 여러 곳에서 참조할 수 있습니다. 또한 런타임에 CSS를 동적으로 바꾸는 것도 가능해지는데, 이는 이전에는 CSS 전처리기가 필요했던 일입니다. CSS 변수 덕분에 브랜드나 테마에 맞게 Ionic 컴포넌트를 덮어쓰는 것이 그 어느 때보다 쉬워졌습니다.
출처: 문서
본문
Setting Values (값 설정하기)
Global Variables (전역 변수)
CSS 변수는 앱의 :root 선택자 안에서 전역으로 설정할 수 있습니다. 특정 mode에만 적용되도록 할 수도 있습니다. Ionic이 제공하는 전역 변수에 대한 자세한 내용은 Ionic Variables를 참고하세요.
Ionic CLI로 Angular, React 또는 Vue 프로젝트를 시작하면 src/theme/variables.scss 파일이 생성되며, 여기서 기본 Ionic Variables를 덮어쓸 수 있습니다.
/* Set variables for all modes */
:root {
/* Set the background of the entire app */
--ion-background-color: #ff3700;
/* Set the font family of the entire app */
--ion-font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', 'Roboto', sans-serif;
}
/* Set text color of the entire app for iOS only */
:root.ios {
--ion-text-color: #000;
}
/* Set text color of the entire app for Material Design only */
:root.md {
--ion-text-color: #222;
}
Component Variables (컴포넌트 변수)
특정 컴포넌트의 CSS 변수를 설정하려면 해당 컴포넌트의 선택자 안에 변수를 추가하세요. Ionic이 제공하는 컴포넌트 수준 변수에 대한 자세한 내용은 Ionic Variables를 참고하세요.
/* Set the color on all ion-button elements */
ion-button {
--color: #222;
}
/* Set the background on an ion-button with the .fancy-button class */
.fancy-button {
--background: #00ff00;
}
Variables set via JavaScript (JavaScript로 설정하는 변수)
CSS 변수는 setProperty()를 사용해 JavaScript로도 변경할 수 있습니다.
const el = document.querySelector('.fancy-button');
el.style.setProperty('--background', '#36454f');
Getting Values (값 가져오기)
Using CSS (CSS로 읽기)
var() CSS 함수를 사용하면 CSS 변수의 값을 원하는 만큼의 폴백(fallback) 값과 함께 가져올 수 있습니다. 아래 예제에서 --background 속성은 --charcoal 변수가 정의되어 있으면 그 값을 사용하고, 없으면 #36454f를 사용하도록 설정됩니다.
.fancy-button {
--background: var(--charcoal, #36454f);
}
Using JavaScript (JavaScript로 읽기)
CSS 변수의 값은 JavaScript에서 getPropertyValue()를 사용해 읽을 수 있습니다.
const el = document.querySelector('.fancy-button');
const color = el.style.getPropertyValue('--background');
Ionic Variables
Component Variables (컴포넌트 변수)
Ionic은 --background와 --color 같은 컴포넌트 수준에서 존재하는 변수를 제공합니다. 컴포넌트가 받아들이는 사용자 지정 속성 목록을 보려면 API reference의 CSS Custom Properties 섹션을 확인하세요. 예를 들어 Button CSS Custom Properties를 참고할 수 있습니다.
Global Variables (전역 변수)
Ionic은 전체 앱을 테마링하기 쉽도록 여러 전역 변수를 제공합니다. 자세한 내용은 Colors, Themes, Advanced Theming을 참고하세요.
더 알아보기 (Learn more)
이번에는 CSS 변수를 설정하고 값을 읽는 다양한 방법과 Ionic이 제공하는 변수들을 알아봤어요. 다음으로는 Colors 문서와 Themes 문서를 살펴보며 앱 전체의 테마를 다루어 보시길 권합니다.