프론트엔드/React

[React] CSS Modules

tero1115 2026. 3. 12. 22:13

CSS Modules는 CSS 클래스 이름을 컴포넌트 단위로 고유하게 만들어주는 방식

 

다음과 같은 CSS가 있다고 가정

.btn {
  color: white;
  background: tomato;
}

빌드 후 실제 브라우저에서 사용되는 클래스 이름은 이런 형태로 바뀜

Button_btn__3X7a9

클래스 이름에 파일 정보와 랜덤 문자열이 붙어서 고유한 이름이 됨

 


사용방법

1. CSS 파일 생성

CSS Module은 파일 이름에 .module.css를 붙여야함

Button.module.css
.btn {
    color: white;
    background: tomato;
}
 

2. 컴포넌트에서 import

import styles from "./Button.module.css";
 

여기서 styles는 CSS 클래스 이름을 담고 있는 객체

 

3. className에 적용

<button className={styles.btn}>
	버튼
</button>
 

실제로 브라우저에서는 다음과 같이 렌더링됨

<button class="Button_btn__3X7a9">

 


일반 CSS와 차이

일반 CSS

import "./Button.css";
<button className="btn">
 

특징

 - CSS가 전역(Global) 으로 적용됨

 - 같은 클래스 이름이 있으면 충돌 가능

CSS Modules

import styles from "./Button.module.css";
<button className={styles.btn}>
 

특징

 - 클래스 이름을 자동으로 고유하게 생성

 - 컴포넌트 단위 스타일 관리 가능

 - CSS 충돌 방지

'프론트엔드 > React' 카테고리의 다른 글

[React] 기초(6) - nextjs  (0) 2023.10.05
[React] 기초(5) - route  (0) 2023.10.04
[React] 기초(4) - useEffect  (0) 2023.10.04
[React] 기초(3) - useState  (0) 2023.10.04
[React] 기초(1)  (0) 2023.10.04