2025-04-12-Tailwind CSS 簡短複習
2025-04-12-Tailwind CSS 簡短複習
Tailwind CSS 簡短複習(中文重點版)
很好,Tailwind 在現代前端很常見 —— 它不是一個「預做好的元件庫」,而是一個 utility-first(實用類別優先) 的 CSS 工具集。下面把重點、優點、使用方法與實務範例都說清楚,方便你馬上回去套在 Vue 元件上。
什麼是 Tailwind?
- Utility-first:提供大量小而單一職責的 class(像
p-4
、text-sm
、bg-blue-500
),透過組合這些 class 來完成樣式,而不是寫大量自訂 CSS。 - 不預設外觀:不像 Bootstrap 那樣有強烈主題,Tailwind 提供基礎工具,讓你自由打造風格。
- 高度可客製:可以在
tailwind.config.js
裡擴充顏色、間距、字型等。
優點與缺點(實用判斷)
優點
- 快速開發 UI:不用在 CSS 檔案來回切換,直接在 markup 上寫 class。
- 一致性好:團隊上使用同一套 spacing / color scale。
- 生產環境體積小:透過
content
(或 purge)只保留用到的 class,輸出 CSS 很小。 - 易做 RWD:用
sm:
,md:
,lg:
簡單寫響應式。
缺點
- 初期 class 看起來「很長」或「雜」,可用
@apply
抽成 class。 - 習慣上需要改變思維(從寫 CSS 移到組合 class)。
- 若把邏輯產生的 class 亂寫,可能導致無法被 purge(需要注意 content 配置或用 safelist)。
在 Vue + Vite 專案快設定(重點)
已做過的指令回顧:
1 | npm install -D tailwindcss postcss autoprefixer |
index.css
(或 src/index.css
)要有:
1 | @tailwind base; |
tailwind.config.js
最重要的 content
設定:
1 | module.exports = { |
把 index.css
在 main.js
引入:import './index.css'
常用語法範例(最好懂)
- 文字與間距:
text-sm
,text-xl
,p-4
,px-6
,py-2
,m-2
- 色彩與背景:
text-white
,bg-blue-500
,hover:bg-blue-600
- 版型:
flex
,grid
,gap-4
,items-center
,justify-between
- 邊框與陰影:
border
,rounded-lg
,shadow-md
- 響應式:
sm:text-sm md:text-base lg:text-lg
- 偽類:
hover:
,focus:
,active:
範例按鈕:
1 | <button class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md"> |
在 Vue 的實務小技巧
動態 class:可以用
:class
綁定字串或物件:1
<button :class="['px-4 py-2 rounded', isActive ? 'bg-green-500' : 'bg-gray-300']">按我</button>
避免無法 purge 的動態 class:若 class 是由變數拼接(像
bg-${color}-500
),Tailwind 可能無法偵測到。可用 safelist 或在 template 裡列明所有可能的 class。重複樣式抽出:用
@apply
在你的 CSS 裡抽成一個自訂 class(減少長長的 class 列表):1
2
3.btn {
@apply px-4 py-2 rounded bg-blue-500 text-white hover:bg-blue-600;
}表單美化:安裝官方 plugin
@tailwindcss/forms
能快速讓 input/select/look 更好看。
範例:把 InputForm.vue 用 Tailwind 改造
1 | <template> |
最佳實務與建議
- 先熟悉常用 utility(flex、spacing、typography、colors)再用進階功能。
- 用
@apply
抽重複樣式,維持模板可讀性。 - 注意
content
配置,確保生產環境能正確 tree-shake CSS。 - 把設計 token(colors、spacing)放到
tailwind.config.js
的theme.extend
,團隊一致性更好。