728x90
728x90

Tailwind CSS

들어가며

  • 테일윈드(Tailwind) CSS에 대해 정리해본다.

 

Tailwind CSS

개념

  • 유틸리티 우선 CSS 프레임워크
  • 미리 정의된 CSS 클래스를 사용하여 빠르게 사용자 인터페이스를 구축할 수 있도록 도와준다.
  • 전통적인 CSS 프레임워크와 달리, 구성 요소를 만들기 위한 완성된 스타일이 아니라, 각 스타일 속성에 대한 클래스(유틸리티 클래스)를 제공한다.
  • 개발자는 자신의 디자인에 맞게 클래스를 조합하여 원하는 스타일을 쉽게 적용할 수 있다.

 

특징

  •  다양한 스타일 속성을 제어할 수 있는 클래스를 제공한다.
    • 예) @bg-blue-500@ : 배경색을 파란색으로 설정
  • CSS의 재사용성과 모듈화를 강조한다.
    • 클래스 이름이 의미를 가지므로, 다른 프로젝트에서도 쉽게 이해하고 사용할 수 있다.
  • 반응형 디자인을 지원하여, 다양한 화면 크기에서 적절한 스타일을 적용할 수 있다.
    • 예) @md:bg-red-500@ : 중간 크기 이상의 화면에서 배경색을 빨간색으로 설정
  • @tailwind.config.js@ 파일을 통해 스타일을 커스텀 정의할 수 있다. (색상, 간격, 폰트 등 변경 가능)
  • JIT(Just-in-Time) 모드를 제공하여 개발 중에 필요한 클래스만 즉시 생성하여 성능을 최적화하고, 동적으로 생성된 클래스를 사용할 수 있게 해준다.

 

개발환경 구축하기

설치하기

$ npm install -D tailwindcss postcss autoprefixer    # yarn add- -D tailwindcss postcss autoprefixer
$ npx tailwindcss init                               # yarn tailwindcss init

 

⇒ @postcss@ : CSS를 변환하기 위한 도구 (CSS 코드의 자동 포맷팅, 변수 처리, 믹스인 사용 등을 할 수 있음.)

⇒ @autoprefixer@ : CSS 속성에 자동으로 벤더 프리픽스(@-webkit-@, @-moz-@, @-ms-@ 등의 접두사)를 추가해주는 도구

 

템플릿 경로 설정하기 (@tailwind.config.js@)

  • 프로젝트 최상단 경로에 있는 @tailwind.config.js@ 파일에 아래의 내용을 추가한다.
    • 터미널에 @npx tailwindcss init@ 명령을 실행하면 프로젝트 최상단에 @tailwind.config.js@ 파일이 생성된다.
/tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],    // index.html 파일과, src 디렉토리 내의 모든 하위 디렉토리 및 파일에서 .js/.ts/.jsx/.tsx 확장자를 가진 파일
  theme: {
    extend: {},
  },
  plugins: [],
}

 

플러그인 추가해주기 (postcss.config.js)

  • 프로젝트의 최상위 경로에 있는 @postcss.config.js@ 파일에 아래와 같이 플러그인을 추가한다.
    • 만약 해당 파일이 없을 경우 새로 생성해준다.

 

/postcss.config.js
export default {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}

 

⇒ Tailwind CSS와 Autoprefixer를 PostCSS 플러그인으로 사용하도록 지정한다.

 

CSS 파일에 포함시키기

  • @/src@ 경로에 있는 @index.css@ 파일에 아래의 내용을 추가해준다.

 

/src/index.css
@tailwind base;
@tailwind components;
@tailwind utilities;

 

⇒ @base@ : 테일윈드의 기본 리셋기본 스타일 포함하기 (브라우저의 기본 스타일 초기화, 기본적인 HTML 요소들에 대한 스타일 설정)

⇒ @components@ : 테일윈드의 컴포넌트 스타일 포함하기 (버튼, 카드, 폼과 같은 재사용 가능한 UI 컴포넌트에 대한 기본 스타일 제공)

⇒ @utilities@ : 테일윈드의 유틸리티 클래스 포함하기 (@flex@, @padding@, @margin@, @color@ 등과 같은 다양한 유틸리티 클래스 제공)

 

  • 만약 @index.css@ 파일에서 아래와 같은 경고 메시지가 표시되면 VS Code에서 @PostCSS Language Support@ 확장을 설치해준다.

경고 메시지가 표시되는 모습

 

PostCSS Language Support - Visual Studio Marketplace

Extension for Visual Studio Code - Syntax highlighting for modern and experimental CSS in VSCode

marketplace.visualstudio.com

 

빌드하기

  • 이제 @src@ 폴더 안에 있는 파일에서 테일윈드 CSS를 사용하면 된다.
<div class="bg-blue-500 text-white p-4 rounded-lg">
  Hello, Tailwind CSS!
</div>

 

커스텀 속성 추가하기

커스텀 색상

  • 테일윈드의 기본 색상 팔레트를 확장하여 프로젝트에 맞는 커스텀 색상을 추가할 수 있다.
  • 프로젝트 최상위 경로에 있는 @tailwind.config.js@ 파일의 @theme.extend@ 섹션에 커스텀 색상 속성을 추가해준다.
    • 키 값@colors@로 지정해준다.

 

./tailwind.config.js
// tailwind.config.js
module.exports = {
  // ...
  theme: {
    extend: {
      colors: {
        primary: {
          light: '#6D28D9',
          DEFAULT: '#5B21B6',
          dark: '#4C1D95',
        },
        secondary: {
          light: '#FDE68A',
          DEFAULT: '#FCD34D',
          dark: '#FBBF24',
        },
      },
    },
  },
  // ...
}

 

  • 위에서 추가한 커스텀 색상 속성을 아래와 같이 적용시킬 수 있다.
<div className="bg-primary text-white p-4">
  Primary 배경
</div>

<div className="bg-secondary-dark text-black p-4">
  Secondary Dark 배경
</div>

 

커스텀 간격

  • 프로젝트에 필요한 고유한 간격(마진, 패딩 등)을 추가하여 일관된 레이아웃을 유지시킬 수 있다.
  • 프로젝트 최상위 경로에 있는 @tailwind.config.js@ 파일의 @theme.extend@ 섹션에 커스텀 간격 속성을 추가해준다.
    • 키 값을 @spacing@으로 지정해준다.

 

./tailwind.config.js
// tailwind.config.js
module.exports = {
  // ...
  theme: {
    extend: {
      spacing: {
        '72': '18rem',    // 기존 spacing에 72 추가 (사용 예: w-72)
        '84': '21rem',
        '96': '24rem',
      },
    },
  },
  // ...
}

 

  • 아래와 같이 적용시킬 수 있다.
<div className="w-72 h-72 bg-gray-200">
  너비와 높이가 18rem인 박스
</div>

<div className="mt-84">
  상단 마진이 21rem인 요소
</div>

 

커스텀 폰트

  • @/src@ 경로에 있는 @index.css@ 파일에 다음과 같이 @@font-face@ 규칙을 추가해준다.

 

./src/index.css
/* src/styles.css */
@font-face {
  font-family: 'CustomFont';
  src: url('/fonts/CustomFont-Regular.woff2') format('woff2'),
       url('/fonts/CustomFont-Regular.woff') format('woff');
  font-weight: 400;
  font-style: normal;
}

@font-face {
  font-family: 'CustomFont';
  src: url('/fonts/CustomFont-Bold.woff2') format('woff2'),
       url('/fonts/CustomFont-Bold.woff') format('woff');
  font-weight: 700;
  font-style: normal;
}

@tailwind base;
@tailwind components;
@tailwind utilities;

 

  • @tailwind.config.js@ 파일에 위에서 추가한 폰트를 추가해준다.

 

./tailwind.config.js
// tailwind.config.js
module.exports = {
  // ...
  theme: {
    extend: {
      fontFamily: {
        custom: ['CustomFont', 'sans-serif'],    // 커스텀 폰트 추가
      },
    },
  },
  // ...
}

 

  • 아래와 같이 적용시킬 수 있다.
<p className="font-custom text-lg">
  커스텀 폰트가 적용된 텍스트
</p>

 

커스텀 브레이크 포인트

  • 프로젝트 최상위 경로에 있는 @tailwind.config.js@ 파일의 @theme.extend@ 섹션에 커스텀 브레이크 포인트를 추가해준다.
    • 키 값을 @screens@으로 지정해준다.
// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      screens: {
        '3xl': '1600px', // 새로운 브레이크포인트 추가
        // 기존 브레이크포인트 수정
        'sm': '600px',
        'md': '800px',
        'lg': '1200px',
        'xl': '1400px',
        '2xl': '1800px',
      },
    },
  },
  plugins: [],
}

 

  • 아래의 같이 적용시킬 수 있다.
<div class="sm:bg-red-500 md:bg-green-500 lg:bg-blue-500 3xl:bg-emerald-500">

 

커스텀 유틸리티 클래스

  • 테일윈드의 유틸리티 클래스를 조합하여 새로운 유틸리티 클래스를 생성할 수 있다.
    • 이 작업을 통해 반복적인 스타일을 간소화시킬 수 있다.
  • @/src@ 경로에 있는 @index.css@ 파일에 다음과 같이 @@layer utilities@ 규칙을 추가해준다.
    • 커스텀 클래스명(@.클래스명@)을 지정해준다.
    • 그리고 해당 클래스의 으로 @@apply@ 키워드와 적용시키고자 할 테일윈드 속성들을 넣어준다.

 

./src/index.css
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer utilities {
  .btn-custom {
    @apply bg-primary text-white font-bold py-2 px-4 rounded;
  }

  .card {
    @apply shadow-lg rounded-lg p-6 bg-white;
  }
}

 

  • 아래와 같이 적용시킬 수 있다.
<button className="btn-custom hover:bg-primary-dark">
  커스텀 버튼
</button>

<div className="card">
  <h2 className="text-xl font-bold">카드 제목</h2>
  <p className="mt-2">카드 내용...</p>
</div>

 

커스텀 컴포넌트

  • 커스텀 컴포넌트를 생성하여 프로젝트 전체에서 재사용 가능한 UI 요소를 만들 수 있다.
  • @/src@ 경로에 있는 @index.css@ 파일에 다음과 같이 @@layer components@ 규칙을 추가해준다.
    • 커스텀 클래스명(@.클래스명@)을 지정해준다.
    • 그리고 해당 클래스의 값으로 @@apply@ 키워드와 적용시키고자 할 테일윈드 속성들을 넣어준다.

 

./src/index.css
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
  .navbar {
    @apply flex items-center justify-between flex-wrap bg-primary p-4;
  }

  .navbar-brand {
    @apply text-white font-bold text-xl;
  }

  .navbar-link {
    @apply text-white hover:text-gray-300 px-3 py-2 rounded-md text-sm font-medium;
  }
}

 

  • 아래와 같이 적용시킬 수 있다.
<nav className="navbar">
  <div className="navbar-brand">
    내 사이트
  </div>
  <div>
    <a href="#" className="navbar-link">홈</a>
    <a href="#" className="navbar-link">소개</a>
    <a href="#" className="navbar-link">연락처</a>
  </div>
</nav>

 

함께 사용하면 좋은 것들

  • Tailwind CSS와 함께 사용하면 좋은 것들을 정리해본다.

 

Library

react-icons
$ npm install react-icons    # yarn add react-icons
 

react-icons

SVG React icons of popular icon packs using ES6 imports. Latest version: 5.3.0, last published: a month ago. Start using react-icons in your project by running `npm i react-icons`. There are 7290 other projects in the npm registry using react-icons.

www.npmjs.com

 

React Icons

 

react-icons.github.io

 

Visual Studio Code Extensions

Tailwind CSS IntelliSense
 

Tailwind CSS IntelliSense - Visual Studio Marketplace

Extension for Visual Studio Code - Intelligent Tailwind CSS tooling for VS Code

marketplace.visualstudio.com

 

Tailwind Fold
  • @[Ctrl]@ + @[Alt]@ + @[A]@를 눌러서 긴 클래스명이 보여지거나 닫아지도록 할 수 있다.
 

Tailwind Fold - Visual Studio Marketplace

Extension for Visual Studio Code - Improves code readability by folding class attributes

marketplace.visualstudio.com

 

참고 사이트

 

Installation - Tailwind CSS

The simplest and fastest way to get up and running with Tailwind CSS from scratch is with the Tailwind CLI tool.

tailwindcss.com

 

728x90
728x90