How to Use CSS Modules in Astro for Scoped Styling
In Astro, you can use
CSS Modules by importing a .module.css file into your component and applying the imported class names to your elements. This keeps styles scoped locally to the component, avoiding global conflicts.Syntax
To use CSS Modules in Astro, create a CSS file with the .module.css extension. Import it in your Astro component using import styles from './filename.module.css';. Then, apply styles using class={styles.className} on your HTML elements.
This syntax ensures styles are scoped only to that component, preventing clashes with other styles.
astro
--- import styles from './Button.module.css'; --- <button class={styles.primaryButton}>Click me</button>
Example
This example shows a simple Astro component using a CSS Module to style a button with a blue background and white text. The styles apply only to this button, not globally.
astro
--- import styles from './Button.module.css'; --- <button class={styles.primaryButton}>Click me</button> /* Button.module.css */ .primaryButton { background-color: #007acc; color: white; padding: 0.5rem 1rem; border: none; border-radius: 4px; cursor: pointer; } .primaryButton:hover { background-color: #005fa3; }
Output
A blue button with white text labeled 'Click me' that changes to a darker blue on hover.
Common Pitfalls
- Forgetting to use the
.module.cssextension will cause styles to be global, not scoped. - Not importing the CSS Module or using incorrect import syntax will cause errors or no styles applied.
- Trying to use string class names instead of
styles.classNamewill not apply scoped styles.
astro
--- /* Wrong: global CSS file imported as module */ import styles from './styles.css'; // No .module.css extension <button class={styles.primaryButton}>Click me</button> --- /* Right: use .module.css and import */ import styles from './styles.module.css'; <button class={styles.primaryButton}>Click me</button>
Quick Reference
Remember these key points when using CSS Modules in Astro:
- Use
.module.cssextension for CSS files. - Import styles with
import styles from './file.module.css';. - Apply classes with
class={styles.className}. - Styles are scoped locally to the component.
Key Takeaways
Always name your CSS files with the .module.css extension to enable CSS Modules in Astro.
Import CSS Modules using ES module syntax and apply classes via the imported object.
CSS Modules scope styles locally, preventing global style conflicts.
Avoid using plain string class names when using CSS Modules; always use the imported styles object.
Check your import paths and file extensions carefully to avoid common mistakes.