An Alternative to Scoped `<style>`
CSS Modules
CSS Modules give you scoped class names from a separate `.css` file. Useful if you prefer CSS to live outside the `.astro` file.
What you'll learn
- Author a `.module.css` file
- Import its class names into a component
- Compare to inline `<style>`
Astro’s inline <style> block is great for small components. If
you prefer the CSS in its own file with scoped class names, CSS
Modules are built in (via Vite).
The Pattern
/* Card.module.css */
.card {
border: 1px solid #ddd;
padding: 1rem;
}
.title {
margin: 0 0 0.5rem;
} ---
// Card.astro
import styles from "./Card.module.css";
---
<article class={styles.card}>
<h2 class={styles.title}><slot name="title" /></h2>
<slot />
</article> styles.card becomes something like Card_card__a4kZ at build —
guaranteed unique.
When To Use Which
| Approach | Best for |
|---|---|
Inline <style> | Most cases — keeps everything in one file |
| CSS Module file | Larger components, when you prefer separate CSS |
| Global CSS file | Resets, tokens, typography |
| Tailwind | Utility-first design (next lesson) |
The choice is mostly taste. CSS Modules are popular if you’re coming from React/Next.js conventions.
Combining Class Names
When you need multiple module classes, use class:list:
<button
class:list={[
styles.btn,
isActive && styles["btn--active"],
]}
>
<slot />
</button> Up Next
Tailwind — the utility-first option.
Tailwind →