CSS Module

하니·2025년 4월 18일

CSS 프레임워크

목록 보기
3/4

클래스명 충돌 방지

  • 일반 CSS 사용 시 다른 css 파일임에도 클래스명이 같으면 나중에 로드된 스타일이 이전 스타일을 덮어쓰게 된다.

💠 기본 사용법

📂 파일명.module.css

.wrapper {
	background: black;
    padding: 1rem;
}

.inverted {
    background: white;
    border: 1px solid black;
}

:global .something {
	font-weight: 800;
}

:global : 해당 클래스가 웹페이지에서 전역적으로 사용될 때 사용한다.

📂 파일명.jsx

import styles from "./파일명.module.css";

function 파일명() {
	return(
    	<div className={styles.wrapper}>
      		안녕하세요, 저는 <span className="something">hani</span>에요
      	</div>
    )
}

className={styles.클래스명} : class 지정
className="클래스명" : 전역 class 지정

📂 global.css
공통 색상, 스타일 등은 여기에 작성하고, main이나 App 파일에 import 하면 공용으로 쓸 수 있다.

💠 클래스 이름 2개 이상 적용

import styles from "./파일명.module.css";

function 파일명() {
	return(
    	<div className={`${styles.wrapper} ${styles.inverted}`}>
      		안녕하세요, 저는 <span className="something">hani</span>에요
      	</div>
    )
}

✐ classnames 라이브러리

공식문서
CSS 클래스를 조건부로 설정할 때 유용한 라이브러리

npm install --save classnames
npm install --save @types/classnames # TS 사용 시

기본 사용법

classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'

// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'

// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, { baz: null }, ''); // => 'bar'
  • 사용 전
import styles from './Button.module.css';

function Button({ primary, outline, size, disabled, loading, className }) {
  return (
    <button 
      className={`
        ${styles.button} 
        ${primary ? styles.primary : ''} 
        ${outline ? styles.outline : ''} 
        ${styles[size] || ''} 
        ${disabled ? styles.disabled : ''} 
        ${loading ? styles.loading : ''} 
        ${className || ''}
      `}
      disabled={disabled || loading}
    >
      {loading ? '로딩 중...' : '버튼'}
    </button>
  );
}
  • 사용 후
import cn from 'classnames';
import styles from './Button.module.css';

function Button({ primary, outline, size, disabled, loading, className }) {
  return (
    <button 
      className={cn(
        styles.button,
        {
          [styles.primary]: primary,
          [styles.outline]: outline,
          [styles.disabled]: disabled,
          [styles.loading]: loading
        },
        styles[size], // 'sm', 'md', 'lg' 등의 사이즈 클래스
        className
      )}
      disabled={disabled || loading}
    >
      {loading ? '로딩 중...' : '버튼'}
    </button>
  );
}

참고

기본 사용법

profile
Hi, I am HANI Developer(╹◡╹). .....1hani me?

0개의 댓글