技術 5 分鐘閱讀

Tailwind CSS 實戰技巧:10 個讓你寫更快的 Pattern

Tailwind CSS 實戰技巧:10 個讓你寫更快的 Pattern

前言

自從開始用 Tailwind CSS 之後,就回不去傳統 CSS 了。最近整理了一些常用的 pattern,分享給同樣在用 Tailwind 的開發者。

1. 容器置中的最佳寫法

不用再寫 margin: 0 auto

<div class="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
  <!-- 內容 -->
</div>

2. Flexbox 垂直水平置中

<div class="flex min-h-screen items-center justify-center">
  <div>完美置中</div>
</div>

3. 響應式卡片網格

<div class="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
  <div class="rounded-lg bg-white p-6 shadow-md">卡片 1</div>
  <div class="rounded-lg bg-white p-6 shadow-md">卡片 2</div>
  <div class="rounded-lg bg-white p-6 shadow-md">卡片 3</div>
</div>

4. 文字截斷(單行 & 多行)

<!-- 單行截斷 -->
<p class="truncate">很長的文字...</p>

<!-- 多行截斷(2 行) -->
<p class="line-clamp-2">很長的段落文字...</p>

5. 漸層背景按鈕

<button class="rounded-lg bg-gradient-to-r from-blue-500 to-purple-600 px-6 py-3 text-white transition-all hover:from-blue-600 hover:to-purple-700">
  立即開始
</button>

6. 自訂 Ring 取代 outline

<input class="rounded-md border border-gray-300 px-4 py-2 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 focus:outline-none" />

7. Group Hover 效果

滑鼠移到父元素時,子元素同時變化:

<div class="group cursor-pointer rounded-lg p-4 transition hover:bg-gray-50">
  <h3 class="group-hover:text-blue-600">標題</h3>
  <p class="text-gray-500 group-hover:text-gray-700">描述文字</p>
</div>

8. 深色模式切換

<div class="bg-white text-gray-900 dark:bg-gray-900 dark:text-white">
  <p class="text-gray-600 dark:text-gray-400">自動適應深色模式</p>
</div>

9. 動態間距的排版元件

使用 space-y 取代個別設定 margin:

<div class="space-y-4">
  <p>第一段</p>
  <p>第二段</p>
  <p>第三段</p>
</div>

10. 骨架屏(Skeleton Loading)

<div class="animate-pulse space-y-4">
  <div class="h-4 w-3/4 rounded bg-gray-200"></div>
  <div class="h-4 w-1/2 rounded bg-gray-200"></div>
  <div class="h-32 rounded bg-gray-200"></div>
</div>

額外建議:善用 @apply

當某個元件樣式重複出現太多次,可以抽到 CSS 檔案:

/* app.css */
@layer components {
  .btn-primary {
    @apply rounded-lg bg-blue-600 px-6 py-3 text-white transition hover:bg-blue-700;
  }
}

但切記不要濫用 @apply,它會失去 Tailwind utility-first 的優勢。

搭配 React 使用

這些 pattern 在 React 元件中使用特別順手。搭配 Inertia.js 後,前後端的樣式開發體驗非常一致。

小結

Tailwind CSS 的精髓在於用 utility class 快速組合出各種設計,熟悉這些常用 pattern 後,切版速度會大幅提升。

如果你需要類似的系統,歡迎聯繫討論。

#Tailwind CSS #CSS
Thousand Lab

Thousand Lab