Today Sangmin Learned
article thumbnail
728x90

Next.js에서는 전역적으로 적용하는 글로벌 스타일링을 할 수 있다. 기본적으로 TypeScript 템플릿을 가진 create next app을 하면 있긴 하지만, Next.js가 가진 속성이므로 한번 포스팅해보려고 한다. 우선 CSS 모듈을 적용시키는 것부터 보고, 전역적으로 적용시키는 글로벌 스타일링을 보자.

layout.tsx

import styles from "./layout.module.css";
import { FC } from "react";

interface Props {
  children: any;
}

const Layout: FC<Props> = ({ children }) => {
  return <div className={styles.container}>{children}</div>;
};

export default Layout;

layout.module.css

.container {
  max-width: 36rem;
  padding: 0 1rem;
  margin: 3rem auto 6rem;
}

children을 파라미터로 받아와서 뿌려준다. 이 컴포넌트가 하는 역할은 이 레이아웃을 불러온 페이지에서 저 layout.module.css를 적용시켜줌과 동시에 고유한 클래스를 부여해준다. 이제 이 레이아웃을 적용할 페이지를 하나 만들어보자.

 

pages/posts/first-post.tsx

import Link from "next/link";
import Head from "next/head";
import Layout from "../../components/layout";

export default function FirstPost() {
  return (
    <Layout>
      <Head>
        <title>First Post</title>
      </Head>
      <h1>First post</h1>
      <h2>
        <Link href="/">
          <a>Back to home</a>
        </Link>
      </h2>
    </Layout>
  );
}

보다시피 위의 레이아웃 컴포넌트를 불러온 뒤에 전체를 감싸는 div 형태로 만들어줬다. 이렇게 되면 이 first-post 페이지는 자연스럽게 layout 컴포넌트의 성질을 갖게 된다. 그말은 즉 따로 스타일 설정이 안되어있을 경우 layout.module.css의 적용을 받는다는 뜻이다. 이제 서버를 켜고 확인해보면..

div에 자동으로 layout_container_OOO 형태의 클래스가 부여된 것을 볼 수 있다. 추가로, 컨테이너의 클래스를 갖고있기 때문에 layout.module.css의 적용도 받게된다.

 

이제 글로벌 스타일링을 해볼 차례이다.

styles/globals.css

html,
body {
  padding: 0;
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu,
    Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
  line-height: 1.6;
  font-size: 18px;
}

* {
  box-sizing: border-box;
}

a {
  color: #0070f3;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

img {
  max-width: 100%;
  display: block;
}

 

보다시피 다른 건 특별한 게 없고 링크 태그에 파란색 처리를 해준 게 전부다.

_app.tsx

import '../styles/globals.css'
import type { AppProps } from 'next/app'

function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}
export default MyApp

CRA의 App.tsx와 같은 역할을 하는 게 Next.js에서의 _app.tsx이다. 여기에서 보면 globals.css를 임포트해왔다. 이제 모든 컴포넌트들의 a태그에는 파란색 색상이 입혀진 상태일 것이다. 서버를 켜고 확인해보면

글로벌 스타일링이 잘 적용되어 있는 것을 확인할 수 있다.

주의할 점은, 이 글로벌 스타일링은 무조건 styles/globals.css에서만 가져올 수 있다는 것이다. 그러므로, 실제로 프로젝트를 한다고 했을 때 globals.css는 레이아웃의 전체적인 틀을 잡아주는 역할을 하는 것이 좋다고 볼 수 있겠다.

profile

Today Sangmin Learned

@steadily-worked

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!