Tailwind CSS

Jisoo Shin·2023년 12월 27일

Bigc인턴

목록 보기
2/19

Tailwind CSS란?

: Utility-First 컨셉을 가진 CSS 프레임워크

  • 미리 세팅된 유틸리티 클래스를 활용하는 방식으로 스타일링이 가능

  • Utility-First : 미리 세팅된 유틸리티 클래스를 활용해서 HTML 코드 내에서 스타일링 하는 것

  • CSS의 각 속성들을 클래스에 직관적으로 표현하므로써 효율적으로 사용이 가능해짐


Tailwind의 장점

  1. CSS 사용을 위한 네이밍을 할 필요 X
    • 팀원들간 네이밍 컨벤션을 만들 필요 X
    • 빠른 속도로 개발이 가능

Tailwind의 단점

  1. html 코드가 장황하고 복잡함

    • 모든 요소에 대해 스타일을 적용하기 위해서 class에 원하는 값들을 지속적으로 넣어줘야함
  2. 어떤 목적을 위한 코드인지 구분이 어려워짐

    • 네이밍을 하지 X기 때문에 발생
    • 정확한 네이밍이 되어 있지 X기 때문에 소스를 더욱 더 세밀하게 분석해야할 필요

Tailwind 설정하기

1. 패키지 설치하기

npm install -D tailwindcss postcss autoprefixer style-loader css-loader postcss-loader

2. webpack 설정하기

module.exports = {
    // 로더 등록
    module: {
        rules: [
            {
                test: /\.css?$/,
                use: ['style-loader', 'css-loader', 'postcss-loader'],
                exclude: ['/node_modules/'],
            },
        ],
    },
};

3. tailwind 초기화하기

npx tailwindcss init

  • 이렇게 하면, tailwind의 설정 파일인 tailwind.config.js 파일이 생성되는 것을 확인할 수 있음

  • 아래와 같이 생성됨.

// tailwind.config.js

/** @type {import('tailwindcss').Config} */
module.exports = {
    content: [],
    theme: {
        extend: {},
    },
    plugins: [],
};

4. tailwind 파일 내에 content 설정해주기

  • 위에서 생성된 tailwind.config.js 파일을 보면, content라는 설정 값이 있음
  • content에는 tailwind를 적용할 파일 경로를 넣어주면 되고, 일반적으로 아래와 같이 넣어주면 모든 파일에 tailwind가 적용되는 것을 볼 수 있음.
/** @type {import('tailwindcss').Config} */
module.exports = {
    content: ['./src/**/*.{js,ts,jsx,tsx}'],
    theme: {
        extend: {},
    },
    plugins: [],
};

5. postcss 설정해주기

  • root 경로에 postcss.config.js 파일을 생성해주고 아래와 같이 코드를 작성해주면 됨
module.exports = {
    plugins: {
        tailwindcss: {},
        autoprefixer: {},
    },
};

6. main.css 설정

  • /src 내에서 메인이 되는 css 파일들에 다음과 같이 코드를 작성하여서 tailwind 지시문을 추가함.
@tailwind base;
@tailwind components;
@tailwind utilities;
  • 이후 해당 파일을 전역적으로 사용할 수 있는 파일에 import하여서 전역적으로 적용될 수 있게 함
// index.tsx 또는 App.tsx 같은 파일들에 

import './main.css';

Base style 지정하기 - @apply / @layer 사용

  • Tailwind CSS에서는 Base Style를 추가하고 싶을 때, @layer를 사용할 수 있음.

  • @layer를 사용한다면 Tailwind에서 기본적으로 제공해주는 Base style과 components, utilities를 수정할 수 있음.

  • 위의 06. main.css 에서 tailwind 지시문 추가한 부분 아래에 작성하면 됨.

1. @layer base

: HTML 기본 태그 (h1, p 등), reset rules에 적용될 기본 스타일을 위한 layer

@layer base {
  h1 {
    @apply text-2xl;
  }
}

위의 예시와 같이, @layer를 통해서 h1, h2의 기본 폰트크기를 조정할 수도 있고, a 태그의 기본적인 색깔 등도 수정이 가능함!

2. @layer.components

: 카드, 버튼과 같은 재사용성이 높은 유틸리티 클래스를 만들 때 사용

@layer components {
  .btn {
    @apply inline-block px-4 py-2 rounded-lg shadow-lg bg-blue text-white font-bold mb-5;
  }

}

3. @utilities layer

: tailwind가 제공하지 않은 유틸리티 클래스를 만들때 사용

@layer utilities {
  .fixed-center-x {
    @apply fixed left-1/2 transform -translate-x-1/2;
  }
}

Tailwind를 사용한 예시들

EX1.

다음은 Tailwind를 적용하기 전 (styled-components)를 쓴 방식

<div class="chat-notification">
  <div class="chat-notification-logo-wrapper">
    <img class="chat-notification-logo" src="/img/logo.svg" alt="ChitChat Logo">
  </div>
  <div class="chat-notification-content">
    <h4 class="chat-notification-title">ChitChat</h4>
    <p class="chat-notification-message">You have a new message!</p>
  </div>
</div>

<style>
  .chat-notification {
    display: flex;
    max-width: 24rem;
    margin: 0 auto;
    padding: 1.5rem;
    border-radius: 0.5rem;
    background-color: #fff;
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  }
  .chat-notification-logo-wrapper {
    flex-shrink: 0;
  }
  .chat-notification-logo {
    height: 3rem;
    width: 3rem;
  }
  .chat-notification-content {
    margin-left: 1.5rem;
    padding-top: 0.25rem;
  }
  .chat-notification-title {
    color: #1a202c;
    font-size: 1.25rem;
    line-height: 1.25;
  }
  .chat-notification-message {
    color: #718096;
    font-size: 1rem;
    line-height: 1.5;
  }
</style>

다음은 Tailwind를 적용한 이후의 코드이다.

<div class="p-6 max-w-sm mx-auto bg-white rounded-xl shadow-lg flex items-center space-x-4">
  <div class="shrink-0">
    <img class="h-12 w-12" src="/img/logo.svg" alt="ChitChat Logo">
  </div>
  <div>
    <div class="text-xl font-medium text-black">ChitChat</div>
    <p class="text-slate-500">You have a new message!</p>
  </div>
</div>

Ex2.

import React from 'react';

const App = () => {
    return (
        <div>
            <h2 className="text-blue-500 text-xl font-bold">Hello, React!</h2>
            <p className="text-lg font-medium">Hello, Typescript!</p>
        </div>
    );
};

export default App;

EX3.

// tailwind CSS를 사용하여 가운데 정렬하기

<div class = "flex justify-center items-center">
  <h1> Awesone Tailwind! </h1>
</div>
// 평범한 CSS를 사용하여 가운데 정렬하기

<div>
  <h1>Awesome Tailwind!!</h1>
</div>
<style>
  div {
   display: flex;
   justify-content: center;
   align-items: center;
  }
</style>

VSCode 플러그인 추천

1. Tailwind CSS intelliSense

  • tailwind의 자동완성을 할 수 있게 도와줌

2. Headwind

  • 인라인 클래스 정렬기능

참고 자료

https://velog.io/@woodong/1.-Tailwind-CSS%EB%9E%80

https://jforj.tistory.com/333

https://velog.io/@duckworth/React-%EC%9C%A0%EC%A0%80%EC%9D%98-Tailwind-CSS-%EC%82%AC%EC%9A%A9%ED%95%B4%EB%B3%B4%EA%B8%B0

https://velog.io/@rmaomina/tailwindCSS-apply-rule

// tailwindCss 공식문서
https://tailwindcss.com/docs/responsive-design

0개의 댓글