본문 바로가기
프론트 엔드/Next.js

Next.js에서의 css 스타일링

by 코딩의 세계 2025. 3. 11.

css 스타일링

Next.js에서는 스타일링을 할 수 있는 방법이 여러 가지 존재한다. 이 글에서는 그 부분을 이야기할 것이다.

이번 챕터에서...

다룰 주제는 다음과 같다.

  • 전역 CSS 파일이 무엇인가
  • 스타일링 방법: Tailwind 와 css modules
  • clsx 유틸리티 패키지로 class 명을 조건부로 제공

전역 css

프로젝트를 만들고, src > app 부분을 보면 global.css 파일이 있다. 이 파일이 "전역"으로 css를 먹일 수 있는 파일이다.

이 파일은 앱 내에 어디든 불러올 수 있다.(import) 

근데 보통 최상위 컴포넌트에 추가하는 것이 좋은 관행이다.

  • 예시 코드 > (경로) : src > app > layout.js 
import { Geist, Geist_Mono } from 'next/font/google';
import './globals.css';

const geistSans = Geist({
  variable: '--font-geist-sans',
  subsets: ['latin'],
});

const geistMono = Geist_Mono({
  variable: '--font-geist-mono',
  subsets: ['latin'],
});

export const metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
};

export default function RootLayout({ children }) {
  return (
    <html lang="ko">
      <body className={`${geistSans.variable} ${geistMono.variable}`}>
        {children}
      </body>
    </html>
  );
}

다른 부분은 그다지 신경 안써도 좋다. 중요한 건 

import './globals.css';

이 부분을 작성하는 것이다.

Tailwind

Tailwind 쓰는 사람은 프로젝트 깔 때 yes를 눌러서 잘 깔아 두었을 것이다. (설정은 Next.js가 알아서 해줌)

Tailwind에서는 클래스명을 작성해 요소를 꾸밀 수 있다.

(예시코드)

<h1 className="text-blue-500">I'm blue!</h1>

위 코드는 text-blue-500 클래스를 추가해서 h1 태그의 text를 파랗게 만드는 코드이다.


예시 코드 >

import AcmeLogo from '@/app/ui/acme-logo';
import { ArrowRightIcon } from '@heroicons/react/24/outline';
import Link from 'next/link';
 
export default function Page() {
  return (
    // These are Tailwind classes:
    <main className="flex min-h-screen flex-col p-6">
      <div className="flex h-20 shrink-0 items-end rounded-lg bg-blue-500 p-4 md:h-52">
    // ...
  )
}
css Modules

css Modules은 컴포넌트의 css의 영역 설정이 가능하다.

예시 코드 > (경로) : src > app > page/module.css

.shape {
  height: 0;
  width: 0;
  border-bottom: 30px solid black;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
}

즉, module이 붙어있다면 내가 부분적으로 적용할 css라고 편하게 생각하면 된다.

clsx 라이브러리

clsx는 클래스명을 쉽게 바꾸게 해주는 라이브러리이다.

기본적인 사용법은 다음과 같다.

(설치)

$ npm install --save clsx
  • status를 받는 InvoiceStatus 컴포넌트를 생성한다고 가정하면, 상태는 pending 또는 paid가 될 수 있다.
  • 만약 paid이면 색을 초록색으로 바꾸고, pending이라면 회색으로 한다고 치자. 그럼 아래와 같이 clsx를 사용하여 클래스를 "조건부"로 만들 수 있다.

예시 코드 > (경로) : src > app > ui > invoices >status.tsx

import clsx from 'clsx';
 
export default function InvoiceStatus({ status }: { status: string }) {
  return (
    <span
      className={clsx(
        'inline-flex items-center rounded-full px-2 py-1 text-sm',
        {
          'bg-gray-100 text-gray-500': status === 'pending',
          'bg-green-500 text-white': status === 'paid',
        },
      )}
    >
    // ...
)}

Tailwind을 쓴다는 가정의 코드이다. 이렇게 안 해도 본인이 클래스명을 지정해서 기입해 주면 된다.

'inline-flex items-center rounded-full px-2 py-1 text-sm' 이 부분과 'bg-gray-100 text-gray-500' / 'bg-green-500 text-white' 이 부분에 본인이 지정한 클래스 이름을 넣어주면 끝이다.

clsx에 대한 공식 문서는 다음 링크를 참고하자.

https://github.com/lukeed/clsx

 

GitHub - lukeed/clsx: A tiny (239B) utility for constructing `className` strings conditionally.

A tiny (239B) utility for constructing `className` strings conditionally. - lukeed/clsx

github.com


공식 Next.js 문서

https://nextjs.org/learn/dashboard-app/css-styling

 

App Router: CSS Styling | Next.js

Style your Next.js application with Tailwind and CSS modules.

nextjs.org