Tailwind CSS (NextJs환경에서 사용하기)

Dan·2022년 3월 29일
1

실무공부

목록 보기
4/12
post-thumbnail

오늘은 요즘 핫한 CSS 프레임워크인 Tailwind CSS를 Nextjs 환경에서 적용해보며 배워볼 예정이다.

Tailwind CSS를 왜 사용할까?

Tailwind CSS 는 Utility-First Fundamentals로 이루어진 CSS 프레임워크이다. 아래 예제를 보며 tailwind css를 이해해보자.

<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>

위와 같은 컴포넌트를 만드는데 작성된 코드가 10줄도 안되는 것을 볼 수가 있다. Tailwind CSS를 사용하게 되면 기존 스타일링처럼 class 이름을 생각해내는데 시간 투자를 안해도 된다 또한 styled-component 같이 매번 새로운 컴포넌트를 생성해줄 필요도 없다.

Inline 스타일링이란 다른점은 무엇일까?

코드만 보면 인라인 스타일링하고 매우 유사하지만 굉장히 큰 차이점이 존재한다.

반응형 디자인 : tailwind css는 Inline 과 다르게 반응형이 지원된다.
상태 변화 : tailwind css는 hover , focus 같은 상태 변화 스타일링이 가능하다.

Next.js 환경에서 Tailwind CSS 사용하기

이제 Tailwind CSS의 장점을 알아보았으니 Next.js 환경에서 사용해보도록 하자.

  1. 먼저 Next.js 프로젝트를 생성해보자

npx create-next-app my-project
cd my-project

  1. Tailwind CSS를 프로젝트에 설치하자 (postcss , autoprefixer 도 함께 설치)

npm install -D tailwindcss postcss autoprefixer

  1. Tailwind configs 파일을 만들기 위해 초기화 커맨드를 써주자

npx tailwindcss init -p

  1. 생성된 Tailwind.configs.js 파일에서 Tailwind를 적용시키 파일들의 path를 정해주자
module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
  1. 프로젝트에 기본적으로 Tailwind CSS를 쓸 수 있게 globals.css파일에 @tailwind를 추가해주자

./styles/global.css
@tailwind base;
@tailwind components;
@tailwind utilities;

  1. 마지막으로 프로젝트에 tailwind css를 적용시키고 빌드를 진행하자.
export default function Home() {
  return (
    <h1 className="text-3xl font-bold underline">
      Hello world!
    </h1>
  )
}

npm run dev

참고

profile
만들고 싶은게 많은 개발자

0개의 댓글