🚀 專題一:Tailwind CSS 實戰開始
我們先從最能直接提升成就感的 Tailwind CSS 開始。
1. 安裝 Tailwind
在你的專案目錄執行:
npx astro add tailwind
(全部選 Yes,這會自動設定 astro.config.mjs 並引入指令)
1.設定 astro.config.mjs
// @ts-check
import { defineConfig } from 'astro/config'
import react from '@astrojs/react'
import vercel from '@astrojs/vercel'
// 👇 自訂引入 tailwind
import tailwindcss from '@tailwindcss/vite'
// https://astro.build/config
export default defineConfig({
integrations: [react()],
adapter: vercel(),
output: 'server',
// 👇 自動設定插件 tailwind
vite: {
plugins: [tailwindcss()],
},
})
2.新增 /src/styles/global.css
@import 'tailwindcss';
2. 實作任務:現代化卡片組件
請建立 src/components/Card.astro:
---
interface Props {
title: string;
description: string;
tags: string[];
}
const { title, description, tags } = Astro.props;
---
<div class="group overflow-hidden rounded-xl border border-slate-200 bg-white transition-all hover:shadow-lg hover:-translate-y-1">
<div class="p-6">
<div class="flex gap-2 mb-3">
{tags.map(tag => (
<span class="text-xs font-medium px-2 py-1 rounded-full bg-indigo-50 text-indigo-600">
{tag}
</span>
))}
</div>
<h3 class="text-xl font-bold text-slate-900 group-hover:text-indigo-600 transition-colors">
{title}
</h3>
<p class="mt-2 text-slate-600 text-sm leading-relaxed">
{description}
</p>
</div>
</div>
在 src/layouts/BaseLayout.astro 加入 ../styles/global.css:
---
import '../styles/global.css'
const { pageTitle, pageName } = Astro.props
const _bodyClass =
pageName == 'index' ? 'bg-white' : pageName == 'about' ? 'bg-gray' : ''
---
...(省略)
📝 專題一練習題
任務目標:使用 Tailwind 重構你的部落格列表頁 (blog.astro)。
- 利用剛才建立的
Card.astro組件。 - 將
blog.astro的文章列表改成 Grid 網格佈局(提示:使用class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6")。
給你的 BaseLayout 加入一個漂亮的導覽列,背景使用半透明模糊效果 (backdrop-blur-md bg-white/70)。
挑戰題: 嘗試在 tailwind.config.mjs 中定義一個你專屬的品牌顏色(例如:brand-orange: '#ff5d01'),並在頁面中使用 text-brand-orange。
下個章節是實作筆記 👍