Tailwind CSS 완벽 가이드 - React와 React Native에서 설치부터 활용까지
CSS 파일 만들고, 클래스 이름 짓고, 스타일 적용하고… 솔직히 귀찮죠? 저도 처음엔 CSS 작성하는 게 제일 싫었어요. 그런데 Tailwind CSS를 알고 나서 완전 달라졌습니다.
Tailwind CSS는 “유틸리티 퍼스트” CSS 프레임워크예요. 쉽게 말하면, 미리 만들어진 클래스를 조합해서 스타일링하는 방식입니다. text-red-500이라고 쓰면 빨간색 텍스트가 되고, p-4라고 쓰면 패딩이 적용돼요. CSS 파일 따로 안 만들어도 됩니다.
Tailwind CSS가 뭔가요?
전통적인 CSS는 이렇게 작성하죠:
/* styles.css */
.button {
background-color: blue;
color: white;
padding: 8px 16px;
border-radius: 4px;
}
Tailwind CSS는 HTML에 바로 씁니다:
<button class="bg-blue-500 text-white px-4 py-2 rounded">
버튼
</button>
클래스 이름이 곧 스타일이에요. 익숙해지면 CSS 파일 왔다갔다 할 필요가 없어서 개발 속도가 확 빨라집니다.
Part 1: React에서 Tailwind CSS 설치하기
React 프로젝트에 Tailwind를 설치하는 방법입니다. Vite를 기준으로 설명할게요.
1단계: 프로젝트 생성
npm create vite@latest my-app -- --template react
cd my-app
npm install
2단계: Tailwind CSS 설치
npm install tailwindcss @tailwindcss/vite
3단계: Vite 설정 파일 수정
vite.config.js 파일을 열고 Tailwind 플러그인을 추가합니다:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
plugins: [
react(),
tailwindcss(),
],
})
4단계: CSS 파일에 Tailwind 임포트
src/index.css 파일을 열고 맨 위에 추가합니다:
@import "tailwindcss";
기존에 있던 CSS는 지워도 됩니다.
5단계: 테스트
App.jsx에서 테스트해봐요:
function App() {
return (
<div className="min-h-screen bg-gray-100 flex items-center justify-center">
<h1 className="text-4xl font-bold text-blue-600">
Hello Tailwind!
</h1>
</div>
)
}
export default App
개발 서버를 실행하면:
npm run dev
파란색 큰 글씨가 화면 정중앙에 보이면 성공!
React에서 자주 쓰는 Tailwind 패턴
버튼 스타일링
<button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
클릭
</button>
bg-blue-500: 배경색 파랑hover:bg-blue-700: 마우스 올리면 더 진한 파랑py-2 px-4: 세로 패딩 0.5rem, 가로 패딩 1remrounded: 모서리 둥글게
카드 컴포넌트
<div className="max-w-sm rounded-lg shadow-lg overflow-hidden bg-white">
<img className="w-full h-48 object-cover" src="..." alt="..." />
<div className="p-6">
<h2 className="text-xl font-semibold mb-2">제목</h2>
<p className="text-gray-600">설명 텍스트...</p>
</div>
</div>
반응형 디자인
Tailwind는 반응형이 정말 쉬워요:
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{/* 모바일: 1열, 태블릿: 2열, 데스크탑: 3열 */}
</div>
md:: 768px 이상에서 적용lg:: 1024px 이상에서 적용xl:: 1280px 이상에서 적용
Flexbox 레이아웃
// 가로 정렬
<div className="flex items-center justify-between">
<span>왼쪽</span>
<span>오른쪽</span>
</div>
// 세로 중앙 정렬
<div className="flex flex-col items-center justify-center min-h-screen">
<p>화면 정중앙</p>
</div>
Part 2: React Native에서 Tailwind CSS 설치하기
React Native에서는 NativeWind라는 라이브러리를 사용합니다. Tailwind 문법을 React Native에서 쓸 수 있게 해줘요.
Expo 프로젝트 기준 설치
1단계: NativeWind 설치
npm install nativewind
npm install --save-dev tailwindcss
2단계: Tailwind 설정 파일 생성
npx tailwindcss init
3단계: tailwind.config.js 수정
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./App.{js,jsx,ts,tsx}",
"./app/**/*.{js,jsx,ts,tsx}",
"./components/**/*.{js,jsx,ts,tsx}",
"./screens/**/*.{js,jsx,ts,tsx}",
],
presets: [require("nativewind/preset")],
theme: {
extend: {},
},
plugins: [],
};
content 배열에 Tailwind 클래스를 사용할 파일 경로를 넣어야 해요. 안 넣으면 스타일이 적용 안 됩니다.
4단계: babel.config.js 수정
module.exports = function (api) {
api.cache(true);
return {
presets: [
["babel-preset-expo", { jsxImportSource: "nativewind" }],
"nativewind/babel",
],
};
};
5단계: Global CSS 파일 생성
프로젝트 루트에 global.css 파일을 만듭니다:
@tailwind base;
@tailwind components;
@tailwind utilities;
6단계: Metro 설정
metro.config.js 파일을 만들고:
const { getDefaultConfig } = require("expo/metro-config");
const { withNativeWind } = require("nativewind/metro");
const config = getDefaultConfig(__dirname);
module.exports = withNativeWind(config, { input: "./global.css" });
7단계: App.js에서 CSS 임포트
import "./global.css";
export default function App() {
return (
<View className="flex-1 items-center justify-center bg-white">
<Text className="text-2xl font-bold text-blue-500">
Hello NativeWind!
</Text>
</View>
);
}
React Native에서 자주 쓰는 패턴
기본 레이아웃
import { View, Text } from 'react-native';
export default function Screen() {
return (
<View className="flex-1 bg-gray-100 p-4">
<Text className="text-xl font-bold text-gray-800">
제목
</Text>
<Text className="text-gray-600 mt-2">
설명 텍스트
</Text>
</View>
);
}
버튼 스타일링
import { TouchableOpacity, Text } from 'react-native';
function Button({ title, onPress }) {
return (
<TouchableOpacity
className="bg-blue-500 py-3 px-6 rounded-lg active:bg-blue-700"
onPress={onPress}
>
<Text className="text-white text-center font-semibold">
{title}
</Text>
</TouchableOpacity>
);
}
카드 컴포넌트
<View className="bg-white rounded-xl shadow-md p-4 m-2">
<Text className="text-lg font-bold">카드 제목</Text>
<Text className="text-gray-500 mt-1">카드 설명...</Text>
</View>
입력 필드
import { TextInput } from 'react-native';
<TextInput
className="border border-gray-300 rounded-lg px-4 py-3 text-base"
placeholder="입력하세요"
/>
자주 쓰는 클래스 정리
| 클래스 | 설명 |
|---|---|
flex | display: flex |
flex-1 | flex: 1 (공간 채우기) |
items-center | align-items: center |
justify-center | justify-content: center |
p-4 | padding: 1rem |
m-2 | margin: 0.5rem |
text-xl | font-size: 1.25rem |
font-bold | font-weight: 700 |
bg-blue-500 | 배경색 파랑 |
text-white | 텍스트 흰색 |
rounded-lg | border-radius: 0.5rem |
shadow-md | 중간 그림자 |
주의사항
NativeWind v2 사용 시:
- tailwindcss 3.3.2 버전까지만 호환됩니다
- 최신 버전이 안 되면
npm install tailwindcss@3.3.2로 설치
공통:
content배열에 파일 경로 빠뜨리면 스타일 적용 안 됨- 캐시 문제 생기면
npx expo start -c로 캐시 삭제 후 재시작
Tailwind CSS 익숙해지면 진짜 못 빠져나옵니다. 클래스 이름 외우는 게 처음엔 좀 귀찮은데, 일주일만 쓰면 손에 익어요. 공식 문서 치트시트 켜놓고 개발하다 보면 어느새 외워져 있을 거예요!
← 블로그 목록으로