Astro กับ Tailwind CSS: สร้าง UI สวยงามอย่างรวดเร็ว
#astro13 เม.ย. 2569
ติดตั้ง Tailwind ใน Astro
npx astro add tailwind
คำสั่งนี้จะสร้าง tailwind.config.mjs และตั้งค่าทุกอย่างให้อัตโนมัติ
ใช้ Tailwind ใน Component
---
const { title, description, href } = Astro.props;
---
<a
href={href}
class="group block p-6 bg-white rounded-xl shadow-sm hover:shadow-md transition-all border border-gray-100"
>
<h2 class="text-xl font-bold text-gray-900 group-hover:text-blue-600 transition-colors">
{title}
</h2>
<p class="mt-2 text-gray-600 text-sm leading-relaxed">
{description}
</p>
</a>
Dark Mode
// tailwind.config.mjs
export default {
darkMode: 'class',
content: ['./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}']
};
<html class="dark">
<body class="bg-white dark:bg-gray-900 text-gray-900 dark:text-white">
<slot />
</body>
</html>
Typography Plugin
npm install -D @tailwindcss/typography
// tailwind.config.mjs
export default {
plugins: [require('@tailwindcss/typography')]
};
---
const { Content } = await post.render();
---
<!-- Markdown content จะได้ style สวยงาม -->
<article class="prose prose-lg max-w-none">
<Content />
</article>
Custom Components
---
// src/components/Button.astro
const { variant = 'primary', size = 'md', href } = Astro.props;
const variants = {
primary: 'bg-blue-600 text-white hover:bg-blue-700',
secondary: 'bg-gray-100 text-gray-900 hover:bg-gray-200',
outline: 'border border-gray-300 text-gray-700 hover:bg-gray-50'
};
const sizes = {
sm: 'px-3 py-1.5 text-sm',
md: 'px-4 py-2',
lg: 'px-6 py-3 text-lg'
};
---
<a
href={href}
class={`inline-flex items-center rounded-lg font-medium transition-colors ${variants[variant]} ${sizes[size]}`}
>
<slot />
</a>
สรุป
Astro + Tailwind เป็น combination ที่ทรงพลังมาก ทำให้สร้าง UI ได้เร็วและ CSS ที่ได้มีขนาดเล็กมากเพราะ Tailwind purge unused classes ครับ