📌

「Tailwind CSS From Zero to Production」チュートリアルの実施

2025/01/17に公開

Tailwind CSS: From Zero to Production https://github.com/tailwindlabs/tailwindcss-from-zero-to-production のチュートリアルをやった。

サンプルコードはtailwindcss v2 となっているが、チュートリアルはv3で実施した。

01: Setting Up Tailwind CSS v2.0

@tailwindのディレクティブについて https://tailwindcss.com/docs/functions-and-directives

# modenrize-normailzie cssを使ったcssリセット(margin font-size...)やブラウザサポートcss
@tailwind base
レスポンシブコンポーネント用のcontainerクラスcss
@tailwind component
- ptなどのクラス、shadowクラスなどのユーティリティcss
@tailwind utilities

PostCSSを利用してtailwindcssをインストール https://tailwindcss.com/docs/installation/using-postcss

フロントエンドビルドツールにはviteを利用する

  1. tailwindcssをインストール。
npm init -y
npm install -D tailwindcss postcss autoprefixer vite
  1. PostCSS設定にTailwindを追加する
npx tailwindcss init -p
  1. テンプレートパスを構成する
# tailwind.config.css
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["index.html"],
  theme: {
    extend: {},
  },
  plugins: [],
}
  1. tailwindディレクティブをcssに追加する
# css/tailwind.css
@tailwind base;
@tailwind components;
@tailwind utilities;
  1. buildする

viteでbuild設定する

# pckage.json
  "scripts": {
    "dev": "vite",
  },
npm run dev
  1. HTMLにtailwindcssを書く
# index.html
<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="/css/tailwind.css" rel="stylesheet">
</head>
<body>
  <h1 class="text-4xl font-bold text-center text-blue-500">
    Hello world!
  </h1>
</div>

02: The Utility-First Workflow

  1. バックグラウンドカラーをbg-*クラスを使って指定する。
<body class="bg-gray-100">
</body>
  1. アイコンとパディングをp-*クラスを使って指定する

例えば、

  • p-8はすべてにパディングを指定する。
  • pl-8はleftのみパディングを指定する。
  • pt-8はtopのみパディングを指定する。
  • px-8はleft,rightにパディングを指定する。
  • py-8はtop,rbuttonにパディングを指定する。
<body class="bg-gray-100">
  <div class="px-8 py-12">
    <img src="/img/logo.svg" alt="Workcation">
  </div>
</body>
  1. ロゴサイズの修正

heightクラスをh-*を使って指定する。

<body class="bg-gray-100">
  <div class="px-8 py-12">
    <img class="h-10" src="/img/logo.svg" alt="Workcation">
  </div>
</body>
</div>
  1. 画像の設定

marignクラスをm-*を使って指定する。
画像の角と影を、rounnded-*shadow-*を使って指定する。

<body class="bg-gray-100">
  <div class="px-8 py-12">
    <img class="h-10" src="/img/logo.svg" alt="Workcation">
    <img class="mt-6 rounded-lg shadow-xl" src="/img/beach-work.jpg" alt="Woman workcationinig on the beach">
  </div>
</body>
</div>
  1. コンテンツを作成する

margin、fontsize、fontcolorを指定する。

<body class="bg-gray-100">
  <div class="px-8 py-12">
    <img class="h-10" src="/img/logo.svg" alt="Workcation">
    <img class="mt-6 rounded-lg shadow-xl" src="/img/beach-work.jpg" alt="Woman workcationinig on the beach">
    <h1 class="mt-6 text-2xl font-bold text-gray-900">You can work from anywhere.
      <span class="text-indigo-500">Take advantage of it.</span>
    </h1>
    <p class="mt-2 text-gray-600">Workcation helps you find work-friendly rentals in beautiful locations so you can enjoy some nice weather even when you're not on vacation.</p>
  </div>
</body>
</div>

参考として、space-*クラス https://tailwindcss.com/docs/space を利用すれば、子要素に対して共通でmarginを指定することができる。

  1. ボタンを作成する

要素間の高さを調整するため inline-blockクラス https://tailwindcss.com/docs/display を利用する。

uppercaseクラス https://tailwindcss.com/docs/text-transform で文字を大文字にする。

tracking-*クラス https://tailwindcss.com/docs/letter-spacing で文字幅を調整する

<body class="bg-gray-100">
  ...
    <div class="mt-4">
      <a class="inline-block px-5 py-3 rounded-lg shadow-lg bg-indigo-500 text-white uppercase tracking-wider font-semibold text-sm" href="#">Book your escape</a>
    </div>  
  </div>
</body>

03: Responsive Design

  1. レスポンシブデザイン対応をする。
    max-w-*クラス https://tailwindcss.com/docs/max-width で最大幅を指定する。max-w-mdの最大幅は448px
    mx-autoクラスで leftとrightのmarginを設定する。
<body class="bg-gray-100">
  <div class="px-8 py-12 max-w-md mx-auto">
...
  1. sm:ブレイクポイントを指定する。

小さいブレイクポイントから始めること
https://tailwindcss.com/docs/responsive-design

smブレイクポイントはtablet想定

      'tablet': '640px',
      // => @media (min-width: 640px) { ... }

      'laptop': '1024px',
      // => @media (min-width: 1024px) { ... }

      'desktop': '1280px',
      // => @media (min-width: 1280px) { ... }
<body class="bg-gray-100 sm:bg-yellow-300 md:bg-green-500 lg:bg-pink-500 xl:bg-blue-500 2xl:bg-red-500">
  <div class="px-8 py-12 max-w-md mx-auto sm:max-w-xl">
    <img class="h-10" src="/img/logo.svg" alt="Workcation">
    <img class="mt-6 rounded-lg shadow-xl sm:mt-8 sm:h-64 sm:w-full sm:object-cover object-center" src="/img/beach-work.jpg" alt="Woman workcationinig on the beach">
    <h1 class="mt-6 text-2xl font-bold text-gray-900 sm:mt-8 sm:text-4xl">You can work from anywhere.
      <span class="text-indigo-500">Take advantage of it.</span>
    </h1>
    <p class="mt-2 text-gray-600 sm:mt-4 sm:text-xl">Workcation helps you find work-friendly rentals in beautiful locations so you can enjoy some nice weather even when you're not on vacation.</p>
    <div class="mt-4 sm:mt-6">
      <a class="inline-block px-5 py-3 rounded-lg shadow-lg bg-indigo-500 text-white uppercase tracking-wider font-semibold text-sm sm:text-base" href="#">Book your escape</a>
    </div>
  </div>
</body>
  1. lgブレイクポイントを設定する

class="hidden lg:block"lgブレイクポイントの場合に表示されるようにする。

    <img class="hidden lg:block" src="/img/beach-work.jpg" alt="Woman workcationinig on the beach">
  1. gridを指定して、lgブレイクポイントの場合に2分割にする

lg:grid-cols-2lgブレイクポイントの場合に画面を2分割する。
<br class="hidden lg:inline">
で、文章の改行をlgブレイクポイントで指定する

<body class="bg-gray-100 sm:bg-yellow-300 md:bg-green-500 lg:bg-pink-500 xl:bg-blue-500 2xl:bg-red-500">
  <div class="bg-gray-100 grid grid-cols-1 lg:grid-cols-2">
    <div class="px-8 py-12 max-w-md mx-auto sm:max-w-xl lg:px-12 lg:py-24 lg:max-w-full">
      <img class="h-10" src="/img/logo.svg" alt="Workcation">
      <img class="mt-6 rounded-lg shadow-xl sm:mt-8 sm:h-64 sm:w-full sm:object-cover object-center lg:hidden" src="/img/beach-work.jpg" alt="Woman workcationinig on the beach">
      <h1 class="mt-6 text-2xl font-bold text-gray-900 sm:mt-8 sm:text-4xl lg:text-3xl">
        You can work from anywhere.
        <br class="hidden lg:inline">
        <span class="text-indigo-500">Take advantage of it.</span>
      </h1>
      <p class="mt-2 text-gray-600 sm:mt-4 sm:text-xl">Workcation helps you find work-friendly rentals in beautiful locations so you can enjoy some nice weather even when you're not on vacation.</p>
      <div class="mt-4 sm:mt-6">
        <a class="inline-block px-5 py-3 rounded-lg shadow-lg bg-indigo-500 text-white uppercase tracking-wider font-semibold text-sm sm:text-base" href="#">Book your escape</a>
      </div>
    </div>
    <div class="hidden relative lg:block">
      <img class="absolute inset-0 w-full h-full object-cover" src="/img/beach-work.jpg" alt="Woman workcationinig on the beach">
    </div>
  </div>
</body>
</div>
  1. xlブレイクポイントの指定

  2. 2xlブレイクポイントの指定

レスポンシブデザインの完成

<body class="bg-gray-100 sm:bg-yellow-300 md:bg-green-500 lg:bg-pink-500 xl:bg-blue-500 2xl:bg-red-500">
  <div class="bg-gray-100 grid grid-cols-1 lg:grid-cols-2 2xl:grid-cols-5">
    <div class="px-8 py-12 max-w-md mx-auto sm:max-w-xl lg:px-12 lg:py-24 lg:max-w-full xl:mr-0 2xl:col-span-2">
      <div class="xl:max-w-xl">
        <img class="h-10" src="/img/logo.svg" alt="Workcation">
        <img class="mt-6 rounded-lg shadow-xl sm:mt-8 sm:h-64 sm:w-full sm:object-cover object-center lg:hidden" src="/img/beach-work.jpg" alt="Woman workcationinig on the beach">
        <h1 class="mt-6 text-2xl font-bold text-gray-900 sm:mt-8 sm:text-4xl lg:text-3xl xl:text-4xl">
          You can work from anywhere.
          <br class="hidden lg:inline">
          <span class="text-indigo-500">Take advantage of it.</span>
        </h1>
        <p class="mt-2 text-gray-600 sm:mt-4 sm:text-xl">Workcation helps you find work-friendly rentals in beautiful locations so you can enjoy some nice weather even when you're not on vacation.</p>
        <div class="mt-4 sm:mt-6">
          <a class="inline-block px-5 py-3 rounded-lg shadow-lg bg-indigo-500 text-white uppercase tracking-wider font-semibold text-sm sm:text-base" href="#">Book your escape</a>
        </div>
      </div>
    </div>
    <div class="hidden relative lg:block 2xl:col-span-3">
      <img class="absolute inset-0 w-full h-full object-cover" src="/img/beach-work.jpg" alt="Woman workcationinig on the beach">
    </div>
  </div>
</body>

04: Hover, Focus and Other States

https://tailwindcss.com/docs/hover-focus-and-other-states

  1. hover:を指定する

hover:bg-indigo-400 hover:-translate-y-0.5 transform transitionクラスで、hoverしたタイミングでcolorの変更、ボタン位置の変更

  1. focus:を指定する

  2. variantsを指定する

https://v2.tailwindcss.com/docs/configuring-variants

variantsはv2に依存するものなので、下記は指定しなくても動作した。

  variants: {
    extend: {
      backgroundColor: ['active'],
      fontSize: ['hover'],
    },
  },

05: Composing Utilities with @apply

  1. applyを使用する

applyを使って.btnクラスを作成する。
HTML内で.btnクラスにtailwind utilitiesクラスを追加する場合があるため、cssの定義箇所は@tailwind utilities;より前となる。あとに定義した場合は、.btnクラスのpt-*が上書き適用されてしまう。

          <a class="btn px-10" href="#">
            Book your escape
          </a>
@tailwind base;
@tailwind components;
.btn{
    @apply inline-block px-5 py-3 rounded-lg shadow-lg bg-indigo-500 hover:bg-indigo-400 sm:hover:bg-green-500 sm:hover:text-3xl hover:-translate-y-0.5 focus:outline-none focus:ring focus:ring-offset-2 focus:ring-indigo-500 focus:ring-opacity-50 active:bg-indigo-600 transition text-white uppercase tracking-wider font-semibold text-sm sm:text-base
}
@tailwind utilities;
  1. @layer componentsを使用する

@layer componentsを指定すれば、cssの定義順を気にせずに利用できる。
https://tailwindcss.com/docs/functions-and-directives#layer

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
    .btn{
        @apply inline-block px-5 py-3 rounded-lg shadow-lg bg-indigo-500 hover:bg-indigo-400 sm:hover:bg-green-500 sm:hover:text-3xl hover:-translate-y-0.5 focus:outline-none focus:ring focus:ring-offset-2 focus:ring-indigo-500 focus:ring-opacity-50 active:bg-indigo-600 transition text-white uppercase tracking-wider font-semibold text-sm sm:text-base
    }
}
  1. btn-primarybtn-secondaryを作成する

@layer componentsに各クラスを作成して、HTMLで利用する

          <a class="btn btn-primary shadow-lg hover:-translate-y-0.5 transform transition" href="#">Book your escape</a>
          <a class="btn btn-secondary" href="#">Learn more</a>
@layer components {
    .btn {
        @apply inline-block px-5 py-3 rounded-lg focus:outline-none focus:ring focus:ring-offset-2 uppercase tracking-wider font-semibold text-sm sm:text-base;
    }
    .btn-primary {
        @apply bg-indigo-500 text-white hover:bg-indigo-400 focus:ring-indigo-500 focus:ring-opacity-50 active:bg-indigo-600;
    }
    .btn-secondary {
        @apply bg-gray-300 text-gray-800 hover:bg-gray-200 focus:ring-gray-300 focus:ring-opacity-50 active:bg-gray-400;
    }
}

ただし、styleの再利用は推奨はされていない。

https://tailwindcss.com/docs/reusing-styles

06: Extracting Reusable Components

このsectionではreactを利用する。
これまでの章よりはコンポーネントを使ったリファクタリングがメイン。
コードを参照。
https://github.com/tailwindlabs/tailwindcss-from-zero-to-production/tree/main/06-extracting-reusable-components

  1. ループを利用してHTMLの重複を削除することでCSSの重複を削除する
  2. DestinationCardコンポーネントを作成して、CSSをコンポーネントにまとめる。

07: Customizing Your Design System

themeの設定 https://tailwindcss.com/docs/theme

npx tailwindcss init tailwind-full.config.js --full

で、デフォルトのデザインシステムが作成される。

  1. themeにcolorsを指定して拡張する
  theme: {
    extend: {
      colors: {
        brand: "#0fa9e6",
        "brand-light": "#3fbaeb",
        "brand-dark": "#0c87b8",
      }
    },
  },

ネストされたcolorsオブジェクトを指定してグループ化できる。サフィックスの指定されていない値はDEFAULTを指定する。

https://tailwindcss.com/docs/customizing-colors#color-object-syntax

  theme: {
    extend: {
      colors: {
        brand:{
          "brand-light": "#3fbaeb",
          DEFAULT: "#0fa9e6",
          "brand-dark": "#0c87b8",
        }
      }
    },
  },

のようにも書ける。

  1. fontFamilyの指定する

08: Optimizing for Production

  1. vite buildで本番用のcssを作成する

10kBのcssが作成される。zipの場合は2kB。

https://tailwindcss.com/docs/optimizing-for-production

npm run build

✓ 2 modules transformed.
dist/index.html                        4.89 kB │ gzip: 2.01 kB
dist/assets/beach-work-21h_c_dQ.jpg  653.95 kB
dist/assets/index-DbLm9Em8.css        10.64 kB │ gzip: 2.78 kB
✓ built in 348ms

ラップアップ

  • tailwindcssはユーティリティファーストでクラスを指定する。
  • html,js内で利用するcssのみを本番用に出力してcssファイルサイズを最適化する
  • tailwindドキュメントにcolorsパレットをを作成するサイトが紹介されていた

https://tailwindcss.com/docs/customizing-colors#generating-colors
https://uicolors.app/create

  • 他にもtailwindチャンネルに動画がある

https://www.youtube.com/@TailwindLabs/featured

Discussion