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?

🎨 CSSを基礎から深く学ぼう【第四回・最終回】Tailwind CSS・shadcn/ui・CSS Modules・フレームワーク完全解説

0
Posted at

1. 👋 はじめに

前回までで、CSSの基礎からアニメーション・最新機能まで学びました。

最終回は CSSフレームワーク・UIライブラリ を解説します!

「なぜフレームワークを使うのか?」
CSSをゼロから書くのは時間がかかります。
フレームワークを使うことで、開発速度が劇的に向上します。
ただし「素のCSSを理解した上で使う」ことが重要です。
ここまでのシリーズで学んだ知識が、フレームワークの理解を深めます!

この記事を読めば:

  • ✅ Tailwind CSSの仕組みと使い方がわかる
  • ✅ shadcn/uiの特徴と使い方がわかる
  • ✅ CSS Modulesの仕組みがわかる
  • ✅ styled-componentsの書き方がわかる
  • ✅ どれを選ぶべきかの判断基準がわかる

2. 🌊 Tailwind CSS

Tailwind CSSとは?

Tailwind CSSとは「ユーティリティクラスをHTMLに直接書くCSSフレームワーク」です。
bg-blue-500text-xlflex などのクラスを組み合わせてスタイルを作ります。

従来のCSSとの比較

<!-- ❌ 従来のCSS:HTMLとCSSを行き来する必要がある -->
<!-- HTML -->
<button class="submit-button">送信</button>

<!-- CSS -->
<style>
.submit-button {
  background-color: #3b82f6;
  color: white;
  padding: 8px 16px;
  border-radius: 6px;
  font-weight: bold;
  transition: background-color 0.2s ease;
}
.submit-button:hover {
  background-color: #2563eb;
}
</style>

<!-- ✅ Tailwind CSS:HTMLにクラスを書くだけ! -->
<button class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md font-bold transition-colors">
  送信
</button>

Tailwindのクラス命名規則

【命名パターン】
プロパティの略語 + サイズ/値

例:
  p-4    → padding: 1rem(16px)
  px-4   → padding-left・padding-right: 1rem
  py-2   → padding-top・padding-bottom: 0.5rem
  pt-8   → padding-top: 2rem

  m-4    → margin: 1rem
  mx-auto → margin-left・margin-right: auto(中央揃え)

  text-xl  → font-size: 1.25rem
  text-gray-700 → color: #374151

  bg-blue-500  → background-color: #3b82f6
  bg-blue-500/50 → 背景色の透明度50%(スラッシュ記法・v3.x以降推奨)
  /* ※ bg-opacity-50 は非推奨。bg-{color}/{opacity} のスラッシュ記法を使いましょう */

  w-full  → width: 100%
  h-screen → height: 100vh
  max-w-lg → max-width: 32rem

  flex    → display: flex
  items-center → align-items: center
  justify-between → justify-content: space-between
  gap-4   → gap: 1rem

  rounded    → border-radius: 0.25rem
  rounded-lg → border-radius: 0.5rem
  rounded-full → border-radius: 9999px(完全な丸)

  shadow     → box-shadow: ...
  shadow-lg  → より大きなbox-shadow

  border     → border-width: 1px
  border-gray-300 → border-color: #d1d5db

Tailwindのスケール

【サイズスケール(1 = 4px)】

1  = 4px
2  = 8px
3  = 12px
4  = 16px
5  = 20px
6  = 24px
8  = 32px
10 = 40px
12 = 48px
16 = 64px
20 = 80px
24 = 96px

例:
  p-4  → padding: 16px
  p-8  → padding: 32px
  m-2  → margin: 8px

よく使うクラス一覧

<!-- レイアウト -->
<div class="flex items-center justify-between gap-4">
<div class="grid grid-cols-3 gap-6">
<div class="w-full max-w-lg mx-auto">

<!-- テキスト -->
<p class="text-sm text-gray-600 font-medium leading-relaxed">
<h1 class="text-3xl font-bold text-gray-900">
<span class="text-blue-500 underline">

<!-- 背景・枠線 -->
<div class="bg-white border border-gray-200 rounded-lg shadow-sm">
<div class="bg-blue-50 border-l-4 border-blue-500 p-4">

<!-- 状態 -->
<button class="hover:bg-blue-600 focus:ring-2 focus:ring-blue-500 active:scale-95 disabled:opacity-50">

レスポンシブ対応

<!-- sm・md・lg・xl のプレフィックスでブレークポイントを指定 -->
<div class="
  flex          <!-- display: flex を忘れずに! -->
  flex-col      <!-- デフォルト:縦並び -->
  md:flex-row   <!-- md(768px)以上:横並び -->
  gap-4
  md:gap-8      <!-- md以上:余白を大きく -->
">

<!-- グリッドのレスポンシブ -->
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">

ダークモード対応

<!-- dark: プレフィックスでダークモード時のスタイル -->
<div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-white">
  <p class="text-gray-600 dark:text-gray-400">テキスト</p>
</div>

Tailwind設定ファイルのカスタマイズ

⚠️ バージョンに注意!
以下は Tailwind CSS v3 の設定例です。
v4(2025年〜) では tailwind.config.js の代わりに
CSSファイル内の @theme ブロックで設定するよう変わりました。
使用するバージョンを確認してから設定しましょう。

// tailwind.config.js(v3 の書き方)
module.exports = {
  content: ["./src/**/*.{html,tsx,jsx}"],
  theme: {
    extend: {
      // 独自のカラーを追加
      colors: {
        brand: {
          50:  "#eff6ff",
          500: "#3b82f6",
          900: "#1e3a8a",
        },
      },
      // 独自のフォントを追加
      fontFamily: {
        sans: ["Noto Sans JP", "sans-serif"],
      },
      // 独自のサイズを追加
      spacing: {
        "18": "4.5rem",  /* w-18・p-18 などが使えるように */
      },
    },
  },
};
/* v4 の書き方:CSSファイル内の @theme で設定する */
@import "tailwindcss";

@theme {
  --color-brand-50: #eff6ff;
  --color-brand-500: #3b82f6;
  --color-brand-900: #1e3a8a;
  --font-sans: "Noto Sans JP", sans-serif;
  --spacing-18: 4.5rem;
}

Tailwind IntelliSense(VS Code拡張機能)

💡 「クラス名を全部覚えなくて大丈夫!」
VS Codeに 「Tailwind CSS IntelliSense」 拡張機能を入れると、クラス名を数文字打つだけで候補が表示されます。
多くの実務エンジニアがこの拡張機能を活用しています😊


3. 🎨 shadcn/ui

shadcn/uiとは?

shadcn/uiとは「コンポーネントのコードを自分のプロジェクトにコピーして使うUIライブラリ」です。
Tailwind CSS + Radix UI をベースにした高品質なコンポーネント集です。

一般的なUIライブラリとの違い

【一般的なUIライブラリ(MUI・Chakra UIなど)】
  npm install → node_modules に入る
  → コードは非表示・ブラックボックス
  → カスタマイズしにくい
  → バージョン依存・破壊的変更のリスク

【shadcn/ui】
  npx shadcn add button → src/components/ui/button.tsx が作られる
  → コードが自分のプロジェクトに入る
  → 自由に編集できる!
  → バージョン依存なし
  → TypeScript + Tailwind で型安全

インストールと使い方

# プロジェクトのセットアップ(Next.js + TypeScriptが前提)
npx shadcn@latest init

# コンポーネントを個別に追加する
npx shadcn@latest add button
npx shadcn@latest add input
npx shadcn@latest add card
npx shadcn@latest add dialog
npx shadcn@latest add form
// src/components/ui/button.tsx が自動生成される
// 中身は普通のReactコンポーネント + Tailwind CSS

// 使い方
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

const LoginForm = () => {
  return (
    <Card className="w-full max-w-sm">
      <CardHeader>
        <CardTitle>ログイン</CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        <Input type="email" placeholder="メールアドレス" />
        <Input type="password" placeholder="パスワード" />
        <Button className="w-full">ログイン</Button>
      </CardContent>
    </Card>
  );
};

shadcn/ui のvariant(バリアント)

// Button コンポーネントはvariantで見た目を変えられる
<Button variant="default">デフォルト(青)</Button>
<Button variant="destructive">危険(赤)</Button>
<Button variant="outline">アウトライン</Button>
<Button variant="secondary">セカンダリ</Button>
<Button variant="ghost">ゴースト(透明)</Button>
<Button variant="link">リンク風</Button>

// sizeで大きさを変えられる
<Button size="sm"></Button>
<Button size="default">標準</Button>
<Button size="lg"></Button>
<Button size="icon">アイコン用</Button>

shadcn/ui のテーマカスタマイズ

⚠️ バージョンに注意!
shadcn/ui のテーマ変数の形式はバージョンによって異なります。

  • 旧バージョン → HSL形式(--primary: 221.2 83.2% 53.3%
  • 新バージョン → OKLCH形式(--primary: oklch(0.623 0.214 259.8)

使用しているshadcn/uiのバージョンに合わせて記述形式を統一しましょう。

/* globals.css:CSS変数でテーマをカスタマイズ(旧バージョン・HSL形式) */
@layer base {
  :root {
    --background: 0 0% 100%;
    --foreground: 222.2 84% 4.9%;
    --primary: 221.2 83.2% 53.3%;      /* ← ここを変えるだけで全体の色が変わる */
    --primary-foreground: 210 40% 98%;
    --radius: 0.5rem;                   /* ← 角丸の大きさ */
  }

  .dark {
    --background: 222.2 84% 4.9%;
    --foreground: 210 40% 98%;
    --primary: 217.2 91.2% 59.8%;
  }
}

4. 📦 CSS Modules

CSS Modulesとは?

CSS Modulesとは「CSSのクラス名を自動的にスコープ化(ローカル化)する仕組み」です。
クラス名の衝突を防ぎます。

使い方

/* Button.module.css */
.button {
  background: #3b82f6;
  color: white;
  padding: 8px 16px;
  border-radius: 6px;
}

.button:hover {
  background: #2563eb;
}

.large {
  padding: 12px 24px;
  font-size: 18px;
}
/* Button.tsx */
import styles from "./Button.module.css";

const Button = ({ children, large = false }) => {
  return (
    <button
      className={`${styles.button} ${large ? styles.large : ""}`}
    >
      {children}
    </button>
  );
};
【CSS Modulesの仕組み】

書いたクラス名:     .button
実際のクラス名:     .Button_button__x7k2p(自動でユニークになる)

→ 他のコンポーネントの .button クラスと衝突しない!

CSS Modulesのメリット・デメリット

メリット デメリット
クラス名の衝突が起きない クラス名をJSで参照するため可読性がやや低下
通常のCSSと同じ書き方 動的なスタイルは少し書きにくい
コンポーネントとCSSがセット TypeScriptの型サポートが限定的
Next.js・Viteで標準サポート

5. 💅 styled-components

styled-componentsとは?

styled-componentsとは「JavaScriptの中にCSSを書く(CSS-in-JS)ライブラリ」です。
コンポーネントとスタイルを1つのファイルにまとめられます。

インストール

npm install styled-components
npm install -D @types/styled-components  # TypeScript用

基本的な使い方

import styled from "styled-components";

/* styled.タグ名`CSS` でスタイル付きコンポーネントを作る */
const Button = styled.button`
  background: #3b82f6;
  color: white;
  padding: 8px 16px;
  border-radius: 6px;
  font-weight: bold;
  cursor: pointer;
  transition: background 0.2s ease;

  &:hover {
    background: #2563eb;
  }
`;

const Title = styled.h1`
  font-size: 2rem;
  font-weight: bold;
  color: #1f2937;
`;

/* 使い方:普通のコンポーネントとして使える */
const App = () => {
  return (
    <div>
      <Title>タイトル</Title>
      <Button>送信</Button>
    </div>
  );
};

Propsに応じた動的スタイル

type ButtonProps = {
  variant?: "primary" | "danger";
  size?: "sm" | "md" | "lg";
};

const Button = styled.button<ButtonProps>`
  padding: ${({ size }) => {
    if (size === "sm") return "4px 8px";
    if (size === "lg") return "12px 24px";
    return "8px 16px";  /* md(デフォルト) */
  }};

  background: ${({ variant }) =>
    variant === "danger" ? "#ef4444" : "#3b82f6"};

  color: white;
  border-radius: 6px;
  cursor: pointer;

  &:hover {
    opacity: 0.9;
  }
`;

/* 使い方 */
<Button variant="primary" size="lg">大きいボタン</Button>
<Button variant="danger" size="sm">小さい危険ボタン</Button>

styled-componentsのメリット・デメリット

メリット デメリット
コンポーネントとスタイルが同じファイルにある バンドルサイズが増える
Propsで動的なスタイルを書きやすい ランタイムでCSSを生成するためパフォーマンスに影響
自動でクラス名が衝突しない React専用(他フレームワークでは使いにくい)
テーマ機能が充実している 近年はTailwindに押されて採用が減少傾向

6. 🤔 どれを選べばいいのか?

比較表

Tailwind CSS shadcn/ui CSS Modules styled-components
種類 ユーティリティCSS コンポーネントライブラリ スコープCSS CSS-in-JS
学習コスト 中(クラス名を覚える) 低(コンポーネントを使うだけ) 低(通常のCSS)
カスタマイズ性 ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ⭐⭐⭐ ⭐⭐⭐⭐
Reactとの相性 ✅ 抜群 ✅ React専用 ✅ 良い ✅ React専用
パフォーマンス ✅ 高い ✅ 高い ✅ 高い ⚠️ ランタイムコスト
現在のトレンド 🔥 非常に高い 🔥 急上昇中 📊 安定 📉 減少傾向
バンドルサイズ 小さい 小さい 小さい 大きくなりがち

プロジェクト別のおすすめ

🌱 学習・個人開発:
  Tailwind CSS
  → 最もシェアが高く・情報が豊富・フリーランスでも需要が高い

🏢 チーム開発・業務アプリ:
  Tailwind CSS + shadcn/ui
  → 高品質なUIを素早く作れる・カスタマイズも自由

📦 既存のCSSを活かしたい:
  CSS Modules
  → 通常のCSSと同じ書き方・Next.jsで標準サポート

🎨 デザインの自由度を重視:
  Tailwind CSS(カスタマイズ)
  → tailwind.config.js で自由にカスタマイズ可能

選び方のフローチャート


7. 🎯 シリーズ総まとめ

4回にわたって学んだCSSの内容を振り返りましょう。

テーマ 重要ポイント
第一回 CSS基礎・セレクター・詳細度 カスケード・継承・CSS変数・@layer
第二回 レイアウト ボックスモデル・Flexbox・Grid・position・レスポンシブ
第三回 アニメーション・高度なCSS transition・animation・:has()・コンテナクエリ・CSS Nesting
第四回 フレームワーク Tailwind・shadcn/ui・CSS Modules・styled-components

良いCSSを書くためのチェックリスト

✅ box-sizing: border-box を全要素に設定しているか
✅ !important を使いすぎていないか(詳細度で解決できないか)
✅ インラインスタイルを使いすぎていないか
✅ CSS変数(カスタムプロパティ)で色・サイズを管理しているか
✅ Flexboxで1方向・Gridで2方向と使い分けているか
✅ position: absolute を使うとき親に relative を忘れていないか
✅ モバイルファーストで書いているか
✅ transition は変化させたいプロパティだけに指定しているか
✅ prefers-reduced-motion でアニメーション削減に対応しているか
✅ フレームワークを使うとき「なぜこのクラスを使うのか」理解しているか

「フレームワークは道具であり、目的ではありません。」

Tailwind・shadcn/uiはとても強力ですが、
素のCSSの仕組みを理解した上で使うことが重要です。
このシリーズで学んだ「なぜ」の理解が、
どんなフレームワークを使っても応用できる力になります💪

「なんとなく書いていたCSS」から「意味を理解して書けるCSS」へ。
4回にわたる学習、お疲れ様でした🎉

💬 質問や感想があれば、コメント欄でお気軽にどうぞ!
👍 役に立ったら、いいね&ストックをお願いします!
🎓 ここまで読んでくださって、本当にありがとうございました!


🔗 シリーズ記事

  • 【第一回】CSSの基礎・セレクター・詳細度・カスケード・CSS変数
  • 【第二回】ボックスモデル・Flexbox・Grid・position・レスポンシブ
  • 【第三回】アニメーション・疑似クラス・高度なCSS・最新機能
  • 【第四回】Tailwind CSS・shadcn/ui・CSS Modules・フレームワーク完全解説(この記事)
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?