0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【備忘録】Next.js 公式チュートリアル Chapter-2 CSS Styling

Last updated at Posted at 2024-02-06

前回

当チャプターの内容

  • グローバルCSSファイルの適用方法
  • TailwindCSSとCSSモジュールの2つのスタイリング方法
  • clsxユーティリティパッケージを使って条件付きのクラス名を追加する方法

なんか最後のやつがよくわからんですが、やっていきましょう。

【公式ドキュメント】Next.js Chapter-2 CSS Styling

Global styles

/app/ui/global.cssを弄るとすべてのルート(ページ)にCSSを適用することができるらしい。
これをグローバルスタイルと呼んでいるらしい。
適用するには/app/layout.tsxにglobal.cssをインポートしましょう。
ということで、layout.tsxを編集します。

lauout.tsx
+ import '@/app/ui/global.css';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}

そして立ち上げたローカルのページを見てみると...

WoWスタイリングされてるじゃないすか!

TailwindCSS

TailwindCSSはCSSのフレームワークで流行りのやつですね。(こういう情報はなんとなく知ってる)
最近はshadcn/uiとかも巷で噂になってたりしますね。

TailwindCSSではCSSファイルにスタイルを記述するのではなくてタグ内のclassNameにスタイルを記述していきます。

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

このようにh1タグにtext-blue-500とクラス名を付与するとテキストが青色になります。
詳しくはTailwindCSS公式ドキュメントをみよう!

CSS Modules

CSSモジュールを使えば自分オリジナルのクラス名を追加することができる

/app/ui/home.module.css
.shape {
  height: 0;
  width: 0;
  border-bottom: 30px solid black;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
}

このように記載し、対象のページでインポートすればオリジナルのスタイリングをオリジナルのクラス名で呼び出すことができる!

/app/page.tsx
import styles from '@/app/ui/home.module.css';
<div className={styles.shape} />;

今回のコースではTailwindCSSを主に使うため紹介程度です。

Using the clsx library to toggle class names

ついによくわからんのきたーという感じですが、意外とわかりました。
clsxというのはライブラリのことで、その時の状態や条件に応じてクラス名を変更することができるらしい。

/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',
        },
      )}
    >
    // ...
)}

上記コードでは状態status
pendingのときは背景・テキストをグレーに
paidのときは背景を緑・テキストを白に
設定するということをやってますね。

Other styling solutions

TailwindCSS以外のスタイリング方法ですが、

  • .css.scss等の普通にSassも使えます
  • styled-jsx styled-componentsemotion 等のCSS-in-JSライブラリも使えます

終了!!

以上でChapter-2 CSS Stylingは終了でした。
次回はChapter-3 Optimizing Fonts and Imagesです!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?