การจัดสไตล์ใน Astro
ใน React เราเลือกใช้ CSS Modules, styled-components, emotion หรือ Tailwind แล้วจัดการ global CSS ผ่าน _app.tsx หรือ layout component การสลับ class ต้องอาศัย clsx(...) หรือ ternary บน className
Astro ใช้ CSS เดิมที่คุณรู้จักอยู่แล้ว ไม่มี syntax ใหม่ให้เรียน สิ่งที่เปลี่ยนคือ ที่อยู่ ของ style และ วิธีกำหนดขอบเขต <style> block ภายในไฟล์ .astro จะถูก scoped อัตโนมัติ โดย compiler ส่วน global CSS ใช้ <style is:global> หรือ import stylesheet ที่ระดับ layout และ Tailwind ก็ทำงานเหมือน Next เลย หลังจากเพิ่ม integration
โมดูลนี้จะพาคุณผ่านแต่ละแนวทางโดยยึดโยงกับสิ่งที่คุณรู้จาก React อยู่แล้ว
บทเรียนในโมดูล
หัวข้อที่มีชื่อว่า “บทเรียนในโมดูล”| บทเรียน | สิ่งที่จะได้เรียนรู้ |
|---|---|
| Scoped Styles | <style> auto-scoped เทียบกับ CSS Modules |
| Global Styles | is:global และ stylesheet imports เทียบกับ _app.tsx |
| CSS Variables และ class:list | define:vars และ class:list เทียบกับ clsx / inline styles |
| Tailwind | เพิ่ม Tailwind ใน Astro เทียบกับ Tailwind ใน Next |
ตัวอย่องเปรียบเทียบ
หัวข้อที่มีชื่อว่า “ตัวอย่องเปรียบเทียบ”// Card.jsx (CSS Modules)import styles from './Card.module.css';import clsx from 'clsx';
export default function Card({ title, featured }) { return ( <div className={clsx(styles.card, featured && styles.featured)}> <h2 className={styles.title}>{title}</h2> </div> );}---// Card.astroconst { title, featured } = Astro.props;---<div class:list={["card", { featured }]}> <h2 class="title">{title}</h2></div>
<style> .card { border: 1px solid #e2e8f0; border-radius: 8px; padding: 1rem; } .title { font-size: 1.25rem; margin: 0; } .featured { border-color: #6366f1; background: #eef2ff; }</style>สังเกตสิ่งที่หายไป: ไม่ต้อง import CSS Module ไม่ต้อง import clsx ไม่ต้องมีไฟล์ .module.css แยก <style> block อยู่คู่กับ component และ compiler จัดการ scoping ให้อัตโนมัติ
ตัวอย่างที่รันได้
หัวข้อที่มีชื่อว่า “ตัวอย่างที่รันได้”---
const title = "Astro Styling Overview";
const featured = true;
---
<html lang="en">
<head><meta charset="utf-8" /><title>Styling</title></head>
<body>
<div class:list={["card", { featured }]}>
<h2 class="title">{title}</h2>
<p>Styles are scoped to this component automatically.</p>
</div>
</body>
</html>
<style>
body { font-family: sans-serif; padding: 2rem; background: #f8fafc; }
.card { border: 2px solid #e2e8f0; border-radius: 8px; padding: 1.5rem; max-width: 360px; }
.title { font-size: 1.4rem; margin: 0 0 .5rem; }
.featured { border-color: #6366f1; background: #eef2ff; }
</style>