blog

Tailwind CSS v4 초기 세팅: Vite 플러그인과 @theme

Front-end / CSS#Tailwind CSS#Vite#디자인 토큰#폰트

Tailwind v4는 설정 방식이 크게 바뀌었다. tailwind.config.js 대신 CSS 파일 안의 @theme 에 디자인 토큰을 선언하고, 사용 중인 클래스도 자동으로 탐지해서 content 설정이 필요 없다. (공식 설치 문서)

1. 설치 (Vite)

Vite 프로젝트는 PostCSS 플러그인 대신 전용 Vite 플러그인을 쓴다.

npm install tailwindcss @tailwindcss/vite

@tailwindcss/postcss는 Vite 플러그인을 쓸 수 없는 환경(Next.js 등)에서 사용하는 패키지다. 둘을 함께 설치할 필요는 없다.

2. Vite 플러그인 등록

// vite.config.ts
import tailwindcss from '@tailwindcss/vite';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [tailwindcss()],
});

3. CSS에서 import

/* src/styles/global.css */
@import 'tailwindcss';

이 CSS 파일을 main.ts에서 import하거나 index.html에 링크한다.

4. 폰트 등록

/* src/styles/global.css */
@font-face {
  font-family: 'Pretendard';
  src: url('/fonts/Pretendard-Regular.woff2') format('woff2');
  font-weight: 400;
  font-style: normal;
  font-display: swap;
}

@font-face {
  font-family: 'Pretendard';
  src: url('/fonts/Pretendard-SemiBold.woff2') format('woff2');
  font-weight: 600;
  font-style: normal;
  font-display: swap;
}

굵기마다 Pretendard-Regular, Pretendard-SemiBold처럼 패밀리 이름을 따로 만들기보다, 하나의 패밀리에 font-weight를 나눠 등록하는 편이 낫다. 그러면 font-semibold 같은 기본 유틸리티를 그대로 쓸 수 있고, 브라우저가 가짜 볼드(faux bold)를 만들지 않는다.

5. 디자인 토큰: @theme

@import 'tailwindcss';

@theme {
  --font-pretendard: 'Pretendard', sans-serif;

  --color-brand-0: #e9f2ff;
  --color-brand-2: #dceaff;
  --color-brand-5: #c8daf6;

  --color-input-warning-default: #fdcdcd;
}
  • --font-* → font-pretendard
  • --color-* → bg-brand-0, text-brand-5, border-input-warning-default 등

v4에서는 변수 이름이 곧 클래스 이름이 되므로, v3에서 중첩 객체(input: { warning: { default: ... } })로 쓰던 색상도 하이픈으로 이어 붙인 변수 하나로 선언한다. 기본 팔레트를 모두 지우고 내 색상만 쓰려면 --color-*: initial;을 먼저 선언한다.

px 단위 유틸리티

v4는 spacing을 --spacing 배수로 계산하므로 p-13, w-37처럼 임의의 숫자 클래스가 별도 설정 없이 동작한다. 1단위를 1px로 쓰고 싶다면 기준값을 바꾼다.

@theme {
  --spacing: 1px; /* p-16 = 16px */
}

6. 기존 JS 설정 파일을 계속 쓰려면

v3의 tailwind.config.ts를 그대로 가져가야 한다면 @config로 불러올 수 있다. 다만 호환용 기능이므로 새 프로젝트는 @theme를 사용한다.

@import 'tailwindcss';
@config '../../tailwind.config.ts';

7. 공통 클래스: @layer와 @utility

@layer base {
  *,
  *::before,
  *::after {
    box-sizing: border-box;
    -webkit-user-drag: none;
  }
}

@layer components {
  .heading-36 {
    @apply text-[36px] font-semibold leading-none;
  }
}

@utility flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

@utility로 정의한 클래스는 hover:flex-center, md:flex-center처럼 variant와 함께 쓸 수 있다.