01-Tailwindcss
1. Tailwindcss
https://tailwindcss.com/docs/installation
- Utility-first CSS framework,
- 즉 미리 정의된 CSS의 특성들을
class를 통해 불러와 적용시키는 형태의 CSS 프레임워크 - 원하는
html요소에class을 부여해주면 바로 사용이 가능하다
- 즉 미리 정의된 CSS의 특성들을
Tailwind CSS: CSS 프레임워크. 미리 정의된 클래스를 사용하여 HTML 스타일을 쉽게 적용할 수 있음- e.g.) bg-blue-500 클래스를 적용하면, 따로 CSS 스타일링 없이도 파란 배경을 만들 수 있음
- e.g.) px-4, mx-4 클래스들을 적용하면, 따로 CSS 스타일링 없이도 padding, margin 관리 가능
클래스 기반: Utility-first라는 개념하에 클래스 이름으로 스타일링 가능. HTML과 CSS의 분리를 최소화하고 재사용성을 높임커스텀 설정: tailwind.config.js 파일을 통해 사용자 정의 스타일 및 구성 제공일관된 디자인: 미리 정의된 클래스로 일관서 있는 디자인 구현 가능반응형 스타일링: 미디어 크기에 맞는 반응형 디자인을 지원하며, 클래스 접두사로 편리하게 제어 가능풍부한 자료: 거대한 커뮤니티와 풍부한 자료, 그리고 Tailwind를 이용한 여러가지 컴포넌트들- Tailwind CSS 공식 문서: https://tailwindcss.com/docs/installation
cf. VSCode 확장기능
- Tailwind CSS IntelliSense : 클래스명 자동완성
- Tailwind Docs : 문서 찾아볼 때 Ctrl + Shipt + P로 검색
1.1 Tailwind 주요 개념
- Utility-First Fundamentals (유틸리티-퍼스트 기본 원칙)
- Handling Hover, Focus, and Other States (호버, 포커스 및 다른 상태 처리)
- Responsive Design (반응형 디자인)
- Dark Mode (다크모드)
- Reusing Styles (스타일 재사용)
- Adding Custom Styles (커스텀 스타일 추가)
- Functions & Directives (함수 및 디렉티브)
- cf. Tailwind CSS 공식 문서 참고: https://tailwindcss.com/docs/utility-first
1.2 Tailwind CSS 장단점
[장점]
- 빠른 개발: 클래스 기반 스타일링을 통해 보다 빠르게 개발할 수 있음
- 커스터마이징: Tailwind 설정 파일을 통해 프로젝트에 맞게 스타일 조정 가능
- 재사용성: 클래스를 재사용해서 일관된 디자인 구현 가능
- 반응형: 클래스 접두사로 반응형 디자인을 간편하게 구현할 수 있음 (ex. lg:text-red-500, md:p-4)
[단점]
- 파일 크기: Tailwind를 사용해서 구현하면 클래스가 복잡해지고, 파일 크기가 커질 수 있음
- 학습 곡선: 처음에는 클래스 기반 스타일링에 익숙하지 않아, 초기 학습 비용이 많이 들어감
2. 기본 사용법
https://tailwindcss.com/docs/installation
shellscript
1npm install -D tailwindcss2npx tailwindcss init
tailwindcss를 사용하고자 하는 경로, 파일 작성(확장자명은 띄워쓰면 안 됨)
javascript
1/** @type {import('tailwindcss').Config} */2module.exports = {3content: ['./src/**/*.{html,js,jsx,ts,tsx}'],4theme: {5extend: {},6},7plugins: [],8}
전역 CSS에 다음 코드 추가 (CRA에서는 index.css 맨 위에 추가)
css
1/* tailwind 기본 스타일 및 확장된 스타일 주입 */2@tailwind base;34/* tailwind 기본 컴포넌트 클래스 및 확장된 컴포넌트 클래스 주입 */5@tailwind components;67/* tailwind 기본 유틸리티 클래스 및 확장된 유틸리티 클래스 주입 */8@tailwind utilities;
2.1 Background
tsx
1import React from 'react'23export default function Background() {4return (5<div className="bg-gray-700" style={{ height: 600 }}>6<div style={{ height: 100 }}>7<div style={{ height: 'inherit' }} class="bg-sky-500/100"></div>8<div style={{ height: 'inherit' }} class="bg-sky-500/75"></div>9<div style={{ height: 'inherit' }} class="bg-sky-500/50"></div>10</div>11</div>12)13}
2.2 TailwindExample
jsx
1import Background from './Background'23export default function TailwindExample() {4return (5<div>6<Background />7</div>8)9}
2.3 App.js
jsx
1// Webpack CSS import2// import 'onsenui/css/onsenui.css';3// import 'onsenui/css/onsen-css-components.css';4// import OnesenUIExample from './components/OnsenUI/OnesenUIExample';5// import AntDesignExample from './components/AntDesign/AntDesignExample';6// import 'semantic-ui-css/semantic.min.css';7// import ReactSemanticUIExample from './components/ReactSemanticUI/ReactSemanticUIExample';8// import 'bootstrap/dist/css/bootstrap.min.css';9// import ReactBootstrapExample from './components/ReactBootstrap/ReactBootstrapExample';10// import MaterialUIExample from './components/MaterialUI/MaterialUIExample';11import TailwindExample from './components/Tailwind/TailwindExample'1213export default function App() {14return (15<>16<TailwindExample />17{/* <MaterialUIExample /> */}18{/* <ReactBootstrapExample /> */}19{/* <ReactSemanticUIExample /> */}20{/* <AntDesignExample /> */}21{/* <OnesenUIExample /> */}22</>23)24}
3. Next.js에서 Tailwind CSS 사용
(1) yarn으로 Tailwind CSS 설치 후, Tailwind CSS 구성 파일 생성을 위해 tailwindcss init 커맨드 입력
shellscript
1yarn add -D tailwindcss postcss autoprefixer2npx tailwindcss init -p
(2) PostCSS 설정 파일에 Tailwind 추가
javascript
1// postcss.config.js2module.exports = {3plugins: {4tailwindcss: {},5autoprefixer: {},6},7}
(3) TailwindCSS를 적용할 템플릿 파일 경로를 tailwind.config.js 설정 파일에 명시한다
javascript
1import type { Config } from 'tailwindcss'23const config: Config = {4content: [5'./src/pages/**/*.{js,ts,jsx,tsx,mdx}',6'./src/components/**/*.{js,ts,jsx,tsx,mdx}',7'./src/app/**/*.{js,ts,jsx,tsx,mdx}',8],9theme: {10extend: {},11},12plugins: [],13}14export default config
(4) Tailwind CSS를 사용하기 위한 CSS 파일 을 생성하고 tailwindcss를 import 한다
css
1/* globals.css */2@tailwind base;3@tailwind components;4@tailwind utilities;
(5) 프로젝트를 시작하고, tailwind 클래스를 적용한다
4. 자주 사용하는 Tailwind CSS 클래스
Tailwind CSS 클래스에는 색상, 폰트, 여백, 길이, 그리드, 플렉스, 테두리 등 여러가지 속성 정의 가능
bg-{color}: 배경색을 지정하는 클래스로, 색상 코드 및 이름 정의 (e.g. bg-indigo-500)text-{color}: 텍스트 색상을 지정하는 클래스로, 색상 코드 및 이름 정의 (e.g. text-red-700)font-{weight}: 폰트 굵기를 지정하는 클래스로, 폰트 굵기 및 이름 정의 (e.g. font-bold, font-[700])p-{size}, m-{size}: 패딩 및 마진을 지정하는 클래스로, 각각의 패딩/마진 크기 정의 (e.g. p-2, m-2)w-{size}, h-{size}: 너비 및 높이를 지정하는 클래스로, 각각의 너비/높이 크기 정의 (e.g. w-1/2, h-64)grid, flex: 그리드와 플렉스를 정의할 때 사용하는 클래스 (e.g. grid grid-rows-4)rounded-{radius}: 요소를 둥글게 만드는 클래스 (e.g. rounded-lg)border-{width}: 테두리의 굵기를 정의할 때 사용하는 클래스 (e.g. border-4)
4.1 Utility-First Fundamentals
- TailwindCSS는 클래스 기반의 스타일링을 사용하며, 다양한 유틸리티 클래스를 통해 스타일 적용
bg-blue-500: 배경색을 파란색으로 지정text-white: 텍스트 색상을 흰색으로 지정p-4: 패딩을 크기 4로 지정
4.2 Handling Hover, Focus, and Other States
- Tailwind CSS는 hover, focus 및 다른 상태에 대한 클래스들을 제공하여 상호작용하는 스타일 처리 가능
hover:bg-red-700: 마우스 호버 상태에서 배경색 변경focus:bg-red-700: 포커스시 배경색 변경focus:outline-none: 포커스시 기본 아웃라인 제거
4.3 Responsive Design
- Tailwind는 반응형 디자인을 위한 클래스를 제공하며, 화면 크기에 따라 스타일 조절 가능
- e.g.
md:bg-red-500은 중간 크기 화면에서 배경색을 빨강으로 변경
4.4 Dark Mode
- Tailwind 다크 모드를 구현하기 위한 클래스를 제공하며,
- 다크 테마와 라이트 테마 간 전환 쉽게 처리할 수 있음
dark:bg-gray-800: 다크모드에서 배경색을 어둡게 변경dark:text-white: 다크모드에서 텍스트 색상 변경
4.5 Reusing Styles
- Tailwind는 클래스를 조합해서 스타일을 재사용할 수 있으며, 사용자 정의 클래스를 생성할 수도 있음
- 자주 사용하는 클래스 코드들을 매번 컴포넌트마다 똑같이 복사하는 것이 아니라,
- 하나의 클래스로 정리해서 재사용할 수 있음
btn-primary: 미리 정의된 클래스를 조합하여 재사용가능한 스타일을 생성함
4.6 Adding Custom Styles
tailwind.config.js파일을 통해서 사용자 정의 스타일 및 커스텀 클래스를 추가할 수 있음- colors에 원하는 색상을 추가하여, tailwind에서 사전에 정의한 색상이 아닌, 사용자가 원하는 색상으로 커스텀 가능
- e.g.
bg-blue: 기존 tailwind 색상이 아닌, #1fb6ff 색상으로 나옴
4.7 Functions & Directives
- Tailwind의 함수와 디렉티브는 Tailwind를 더욱 확장 가능하게 만들어주고, 커스터마이징할 때 유용
- Tailwind에서는 테마 값을 동적으로 읽을 수 있는 theme() 함수와
- 미디어 쿼리를 동적으로 생성할 수 있는 screen() 함수를 제공
- 또한, Tailwind만의 @규칙(at-rule) 디렉티브를 사용해서 조건에 따라 요소의 스타일을 조절 가능
@tailwind: HTML 요소에 Tailwind CSS 클래스를 동적으로 추가 가능@layer: CSS 규칙을 레이어별로 구성할 수 있게 함@apply: CSS 클래스를 동적으로 적용할 수 있음@config: Tailwind CSS 구성 옵션 변경 가능
5. Tailwind CSS Tutorial
5.1 Tailwind Playground 실습
- https://play.tailwindcss.com/ 에서 Tailwind 실습해보기
html
1<!-- 1.rem, px -->2<!-- <div class="w-4 w-[20px] w-4">111</div> -->34<!-- 2. bg, border, border-color, rounded -->5<!-- <div class="bg-pink-400 w-64 h-64 border-8 border-black rounded-[25px]">111</div> -->67<!-- 3. w, h, p(패딩), m(마진) -->8<!-- <div class="w-64 h-64 bg-pink-400 w-[350px] h-[350px] p-4 p-[20px] m-4 mx-10 my-20">111</div> -->910<!-- 4. text-color, text-size, font-bold, cursor -->11<!-- <div class="w-64 h-64 bg-black text-pink-400 text-[50px] font-[100] cursor-pointer">111</div> -->1213<!-- 5. flex, flex-col, justify, item, gap -->14<!-- <div class="h-64 w-64 bg-pink-400 text-[50px] text-black flex justify-center itewms-center">111</div> -->1516<!-- <div class="h-[750px] w-[750px] bg-black flex flex-col justify-center items-center gap-4">17<div class="flex h-64 w-64 items-center justify-center bg-pink-400 text-[50px] text-black">111</div>18<div class="flex h-64 w-64 items-center justify-center bg-pink-400 text-[50px] text-black">222</div>19</div> -->2021<!-- 6. hover, transition -->22<!-- <div class="h-[750px] w-[750px] flex-col items-center justify-center gap-4 bg-black">23<div24class="hover:bg-purple-400 transition flex h-64 w-64 items-center justify-center bg-pink-400 text-[50px] text-black"25>2611127</div>28<div29class="hover:text-purple-400 transition-colors flex h-64 w-64 items-center justify-center bg-pink-400 text-[50px] text-black"30>3122232</div>33</div> -->3435<!-- e.g. 픽트로그램 -- 신호등 + 횡단보도 -->36<section class="bg-neutral-700 flex flex-row justify-between items-center h-[250px] w-full group">37<div class="flex flex-row gap-4 group-hover:bg-yellow-400">38<div class="w-4 h-[150px] bg-white"></div>39<div class="w-4 h-[150px] bg-white"></div>40<div class="w-4 h-[150px] bg-white"></div>41<div class="w-4 h-[150px] bg-white"></div>42<div class="w-4 h-[150px] bg-white"></div>43</div>44<div class="flex flex-row justify-center items-center gap-3">45<div class="w-32 h-32 bg-red-500 rounded-full border-2 border-black hover:bg-red-300 transition"></div>46<div class="w-32 h-32 bg-yellow-500 rounded-full border-2 border-black hover:bg-yellow-300 transition"></div>47<div class="w-32 h-32 bg-green-500 rounded-full border-2 border-black hover:bg-green-300 transition"></div>48</div>49<div class="flex flex-row gap-4 group-hover:bg-pink-400">50<div class="w-4 h-[150px] bg-white"></div>51<div class="w-4 h-[150px] bg-white"></div>52<div class="w-4 h-[150px] bg-white"></div>53<div class="w-4 h-[150px] bg-white"></div>54<div class="w-4 h-[150px] bg-white"></div>55</div>56</section>
5.2 참고 : Prettier
shellscript
1npm install -D prettier prettier-plugin-tailwindcss
해당 플러그인은 tailwindcss 공식 Prettier 플러그인입니다. 클래스명을 tailwindcss가 정한 기준대로 나열해주니 한결 코드가 깔끔해짐