Tailwind CSS 실전 가이드
Tailwind CSS로 빠르고 일관된 UI를 만드는 방법. 실무에서 자주 쓰는 패턴과 팁을 공유합니다.
Tailwind CSS는 유틸리티 우선 CSS 프레임워크입니다. 미리 정의된 클래스를 조합해서 스타일을 만듭니다. 처음에는 HTML이 지저분해 보일 수 있지만, 익숙해지면 개발 속도가 크게 향상됩니다.
Tailwind를 선택하는 이유
기존 CSS 작성 방식에는 몇 가지 문제가 있습니다.
첫째, 클래스 이름 짓기가 어렵습니다. BEM 같은 방법론을 사용해도 일관성을 유지하기 힘듭니다.
둘째, CSS 파일이 계속 커집니다. 사용하지 않는 스타일도 남아있고, 비슷한 스타일이 여러 곳에 중복됩니다.
셋째, 컴포넌트와 스타일이 분리되어 있어서 수정할 때 파일을 왔다 갔다 해야 합니다.
Tailwind는 이런 문제를 해결합니다. 클래스 이름을 고민할 필요 없고, 사용하지 않는 클래스는 빌드 시 제거되며, 스타일이 마크업과 함께 있어서 수정이 쉽습니다.
기본 사용법
Tailwind의 클래스 이름은 직관적입니다.
<div class="flex items-center justify-between p-4 bg-white rounded-lg shadow-md">
<h2 class="text-xl font-bold text-gray-800">제목</h2>
<button class="px-4 py-2 text-white bg-blue-500 rounded hover:bg-blue-600">
버튼
</button>
</div>
각 클래스의 의미는 다음과 같습니다.
- flex: display: flex
- items-center: align-items: center
- p-4: padding: 1rem (16px)
- bg-white: background-color: white
- text-xl: font-size: 1.25rem
- hover:bg-blue-600: 호버 시 배경색 변경
반응형 디자인
Tailwind에서 반응형은 접두사를 붙이는 방식입니다.
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<!-- 모바일: 1열, 태블릿: 2열, 데스크톱: 3열 -->
</div>
<p class="text-sm md:text-base lg:text-lg">
<!-- 화면 크기에 따라 글자 크기 변경 -->
</p>
기본 브레이크포인트는 sm(640px), md(768px), lg(1024px), xl(1280px), 2xl(1536px)입니다.
자주 쓰는 패턴
카드 컴포넌트
<div class="overflow-hidden bg-white rounded-xl shadow-lg">
<img src="/image.jpg" alt="" class="w-full h-48 object-cover" />
<div class="p-6">
<span class="text-sm font-medium text-blue-500">카테고리</span>
<h3 class="mt-2 text-xl font-bold text-gray-900">제목입니다</h3>
<p class="mt-2 text-gray-600 line-clamp-2">
설명 텍스트가 들어갑니다. 두 줄까지만 표시됩니다.
</p>
</div>
</div>
중앙 정렬 컨테이너
<div class="max-w-4xl mx-auto px-4">
<!-- 내용 -->
</div>
플렉스 레이아웃
<!-- 수평 중앙 정렬 -->
<div class="flex items-center justify-center h-screen">
<div>중앙에 배치</div>
</div>
<!-- 양쪽 끝 정렬 -->
<div class="flex items-center justify-between">
<div>왼쪽</div>
<div>오른쪽</div>
</div>
<!-- 간격 있는 정렬 -->
<div class="flex items-center gap-4">
<div>항목 1</div>
<div>항목 2</div>
<div>항목 3</div>
</div>
커스텀 설정
tailwind.config.js에서 테마를 확장할 수 있습니다.
module.exports = {
theme: {
extend: {
colors: {
primary: {
50: '#f0f9ff',
500: '#0ea5e9',
600: '#0284c7',
},
brand: '#FF6B35',
},
fontFamily: {
sans: ['Pretendard', 'sans-serif'],
},
spacing: {
'18': '4.5rem',
},
},
},
};
이제 bg-primary-500, text-brand, font-sans 등으로 사용할 수 있습니다.
컴포넌트 추출
반복되는 스타일은 컴포넌트로 추출하는 것이 좋습니다.
// Button.tsx
interface ButtonProps {
variant?: 'primary' | 'secondary';
children: React.ReactNode;
}
function Button({ variant = 'primary', children }: ButtonProps) {
const baseStyles = 'px-4 py-2 rounded-lg font-medium transition-colors';
const variants = {
primary: 'bg-blue-500 text-white hover:bg-blue-600',
secondary: 'bg-gray-200 text-gray-800 hover:bg-gray-300',
};
return (
<button className={`${baseStyles} ${variants[variant]}`}>
{children}
</button>
);
}
다크 모드
Tailwind에서 다크 모드는 dark: 접두사로 쉽게 구현됩니다.
<div class="bg-white dark:bg-gray-900">
<h1 class="text-gray-900 dark:text-white">제목</h1>
<p class="text-gray-600 dark:text-gray-400">내용</p>
</div>
tailwind.config.js에서 다크 모드 전략을 설정합니다.
module.exports = {
darkMode: 'class', // 또는 'media'
};
실전 팁
clsx 또는 cn 유틸리티 사용
조건부 클래스를 깔끔하게 작성할 수 있습니다.
import { clsx } from 'clsx';
function Button({ disabled, variant }) {
return (
<button
className={clsx(
'px-4 py-2 rounded',
variant === 'primary' && 'bg-blue-500 text-white',
variant === 'secondary' && 'bg-gray-200 text-gray-800',
disabled && 'opacity-50 cursor-not-allowed'
)}
>
버튼
</button>
);
}
VS Code 확장 설치
Tailwind CSS IntelliSense 확장을 설치하면 자동 완성과 미리보기가 지원됩니다. 개발 경험이 크게 향상됩니다.
마무리
Tailwind CSS는 처음 배울 때 클래스 이름을 외워야 한다는 부담이 있습니다. 하지만 며칠만 사용해보면 금방 익숙해집니다.
일관된 디자인 시스템을 빠르게 구축하고 싶다면 Tailwind를 추천합니다.