既存のクラス名にTailwindのスタイルを適用する方法
tailwindcss
投稿日: 2025/11/01
HTMLのクラス名を変更できない状況で、Tailwindのデザインシステムを活用したい場合、@applyディレクティブが強力な解決策となります。
@applyディレクティブとは
@applyは、CSSファイル内でTailwindのユーティリティクラスを既存のクラスに適用できるディレクティブです。これにより、HTMLを変更せずにTailwindのデザインシステムの恩恵を受けることができます。
基本的な使い方
セットアップ
まず、CSSファイルでTailwindをインポートします。
/* styles.css */ @tailwind base; @tailwind components; @tailwind utilities;
シンプルな例
既存のクラスにTailwindのユーティリティを適用します。
.button { @apply bg-blue-500 text-white px-4 py-2 rounded; } .card { @apply bg-white shadow-lg rounded-lg p-6; }
HTMLは変更不要です。
<button class="button">クリック</button> <div class="card">カードコンテンツ</div>
実践的な活用例
ボタンのバリエーション
.btn-primary { @apply bg-blue-600 hover:bg-blue-700 text-white font-semibold py-2 px-6 rounded-lg transition-colors duration-200; } .btn-secondary { @apply bg-gray-200 hover:bg-gray-300 text-gray-800 font-semibold py-2 px-6 rounded-lg transition-colors duration-200; } .btn-danger { @apply bg-red-600 hover:bg-red-700 text-white font-semibold py-2 px-6 rounded-lg transition-colors duration-200; }
フォーム要素
.form-input { @apply w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent; } .form-label { @apply block text-sm font-medium text-gray-700 mb-2; } .form-error { @apply text-red-600 text-sm mt-1; }
レイアウトコンポーネント
.container-custom { @apply max-w-7xl mx-auto px-4 sm:px-6 lg:px-8; } .grid-layout { @apply grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6; } .flex-center { @apply flex items-center justify-center; }
ナビゲーション
.nav-link { @apply text-gray-600 hover:text-blue-600 px-3 py-2 rounded-md text-sm font-medium transition-colors; } .nav-link-active { @apply text-blue-600 bg-blue-50 px-3 py-2 rounded-md text-sm font-medium; }
レスポンシブデザイン
レスポンシブユーティリティも@applyで使用できます。
.responsive-card { @apply p-4 md:p-6 lg:p-8 bg-white rounded-lg shadow; } .responsive-text { @apply text-sm md:text-base lg:text-lg; }
疑似クラスの適用
hover、focus、activeなどの疑似クラスもサポートされています。
.interactive-element { @apply bg-gray-100 hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 active:bg-gray-300 transition-all; }
ダークモード対応
.dark-mode-card { @apply bg-white dark:bg-gray-800 text-gray-900 dark:text-white p-6 rounded-lg; }
まとめ
@applyディレクティブは、既存のHTMLクラス名を変更できない状況でTailwindを活用する強力な方法です。ただし、Tailwindの哲学である「ユーティリティファースト」のアプローチを完全に置き換えるものではありません。適切な場面で使い分けることで、保守性の高いコードベースを実現できます。
使用を推奨するケース
- レガシーコードの段階的な移行
- サードパーティライブラリのスタイル上書き
- 複雑で再利用可能なコンポーネントパターン
- CMSなどでHTMLの編集が制限されている場合
適切に活用して、より効率的なフロントエンド開発を実現しましょう。
yosi
Noh を作ってるエンジニア。
